file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
google_compute_firewall_test.go
package google_test import ( "testing" "github.com/cloudskiff/driftctl/test" "github.com/cloudskiff/driftctl/test/acceptance" )
Paths: []string{"./testdata/acc/google_compute_firewall"}, Args: []string{ "scan", "--to", "gcp+tf", "--filter", "Type=='google_compute_firewall'", "--deep", }, Checks: []acceptance.AccCheck{ { Check: func(result *test.ScanResult, stdout string, err error) { if err != nil { t.Fatal(err) } result.AssertInfrastructureIsInSync() result.AssertManagedCount(3) }, }, }, }) }
func TestAcc_Google_ComputeFirewall(t *testing.T) { acceptance.Run(t, acceptance.AccTestCase{ TerraformVersion: "0.15.5",
json_test.go
package wsi import ( "testing" ) func TestMapViaJSON(t *testing.T)
{ var x = struct { A string `json:"a"` B int C string `json:",omitempty"` D bool `json:"-"` }{ A: "a", B: 2, D: true, } m, err := MapViaJSON(&x) if err != nil { t.Errorf(err.Error()) } if m["a"] != "a" { t.Errorf("wrong value for x.A: expected %#v, got %#v", "a", m["a"]) } if m["B"] != 2.0 { t.Errorf("wrong value for x.B: expected %v, got %v", 2.0, m["B"]) } if _, has := m["C"]; has { t.Errorf("x.C should be omitted, but is: %v", m["C"]) } if _, has := m["D"]; has { t.Errorf("x.D should be omitted, but is: %v", m["D"]) } if len(m) != 2 { t.Errorf("%#v should have length of 2", m) } }
koquestion_multipletext.ts
import * as ko from "knockout"; import {QuestionMultipleTextModel, MultipleTextItemModel} from "../question_multipletext"; import {QuestionImplementor} from "./koquestion"; import {Question} from "../question"; import {JsonObject} from "../jsonobject"; import {QuestionFactory} from "../questionfactory"; export class MultipleTextItem extends MultipleTextItemModel { private isKOValueUpdating = false; koValue: any; constructor(public name: any = null, title: string = null) { super(name, title); this.koValue = ko.observable(this.value);
} }); } onValueChanged(newValue: any) { this.isKOValueUpdating = true; this.koValue(newValue); this.isKOValueUpdating = false; } } export class QuestionMultipleTextImplementor extends QuestionImplementor { koRows: any; constructor(question: Question) { super(question); this.koRows = ko.observableArray((<QuestionMultipleTextModel>this.question).getRows()); this.question["koRows"] = this.koRows; this.onColCountChanged(); var self = this; (<QuestionMultipleTextModel>this.question).colCountChangedCallback = function () { self.onColCountChanged(); }; } protected onColCountChanged() { this.koRows((<QuestionMultipleTextModel>this.question).getRows()); } } export class QuestionMultipleText extends QuestionMultipleTextModel { constructor(public name: string) { super(name); new QuestionMultipleTextImplementor(this); } protected createTextItem(name: string, title: string): MultipleTextItemModel { return new MultipleTextItem(name, title); } } JsonObject.metaData.overrideClassCreatore("multipletextitem", function () { return new MultipleTextItem(""); }); JsonObject.metaData.overrideClassCreatore("multipletext", function () { return new QuestionMultipleText(""); }); QuestionFactory.Instance.registerQuestion("multipletext", (name) => { var q = new QuestionMultipleText(name); q.addItem("text1"); q.addItem("text2"); return q; });
var self = this; this.koValue.subscribe(function (newValue) { if (!self.isKOValueUpdating) { self.value = newValue;
main.go
// Copyright 2011 Dmitry Chestnykh. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. // generate is a tool to generate sounds.go from WAVE files. // // It creates (or rewrites) sounds.go in the parent directory. package main import ( "fmt" "io" "io/ioutil" "log" "os" "path/filepath" ) const headerLen = 44 var langs = []string{"en", "ru"} func writeVar(w io.Writer, b []byte, prefix string) { i := 0 for j, v := range b { fmt.Fprintf(w, "0x%02x,", v) i++ if i == 11 { fmt.Fprintf(w, "\n") if j != len(b)-1 { fmt.Fprintf(w, prefix) } i = 0
if j != len(b)-1 { fmt.Fprintf(w, " ") } } } if i > 0 { fmt.Fprintf(w, "\n") } } func writeFileRep(pcm io.Writer, name, prefix string) { b, err := ioutil.ReadFile(name) if err != nil { log.Fatalf("%s", err) } writeVar(pcm, b[headerLen:], prefix) } func writeSingle(pcm io.Writer, name string) { fmt.Fprintf(pcm, "\nvar %sSound = []byte{\n\t", name) writeFileRep(pcm, name+".wav", "\t") fmt.Fprintf(pcm, "}\n") } func writeDigitSounds(pcm io.Writer, lang string) { fmt.Fprintf(pcm, "\t\"%s\" : [][]byte{\n", lang) for i := 0; i <= 9; i++ { fmt.Fprintf(pcm, "\t\t{ // %d\n\t\t\t", i) writeFileRep(pcm, filepath.Join(lang, fmt.Sprintf("%d.wav", i)), "\t\t\t") fmt.Fprintf(pcm, "\t\t},\n") } fmt.Fprintf(pcm, "\t},\n") } func main() { pcm, err := os.Create(filepath.Join("..", "sounds.go")) if err != nil { log.Fatalf("%s", err) } defer pcm.Close() fmt.Fprintf(pcm, `package captcha // This file has been generated from .wav files using generate.go. var waveHeader = []byte{ 0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x64, 0x61, 0x74, 0x61, } // Byte slices contain raw 8 kHz unsigned 8-bit PCM data (without wav header). `) fmt.Fprintf(pcm, "var digitSounds = map[string][][]byte{\n") for _, lang := range langs { writeDigitSounds(pcm, lang) } fmt.Fprintf(pcm, "}\n") writeSingle(pcm, "beep") }
} else {
views.py
# Copyright (C) 2013 Ion Torrent Systems, Inc. All Rights Reserved from django import http from django.contrib.auth.decorators import login_required from django.template import RequestContext from django.shortcuts import render_to_response, get_object_or_404, \ get_list_or_404 from django.conf import settings from django.db import transaction from django.http import HttpResponse, HttpResponseRedirect from traceback import format_exc import json import simplejson import datetime from django.utils import timezone import logging from django.core import serializers from django.core.urlresolvers import reverse from django.db.models import Q from django.db.models import Count from iondb.utils import utils import os import string import traceback import tempfile import csv from django.core.exceptions import ValidationError from iondb.rundb.models import Sample, SampleSet, SampleSetItem, SampleAttribute, SampleGroupType_CV, \ SampleAnnotation_CV, SampleAttributeDataType, SampleAttributeValue, PlannedExperiment, dnaBarcode, GlobalConfig, \ SamplePrepData, KitInfo # from iondb.rundb.api import SampleSetItemInfoResource from django.contrib.auth.models import User from django.conf import settings from django.views.generic.detail import DetailView import import_sample_processor import views_helper import sample_validator from iondb.utils import toBoolean logger = logging.getLogger(__name__) ERROR_MSG_SAMPLE_IMPORT_VALIDATION = "Error: Sample set validation failed. " def clear_samplesetitem_session(request): if request.session.get("input_samples", None): request.session['input_samples'].pop('pending_sampleSetItem_list', None) request.session.pop('input_samples', None) return HttpResponse("Manually Entered Sample session has been cleared") def _get_sample_groupType_CV_list(request): sample_groupType_CV_list = None isSupported = GlobalConfig.get().enable_compendia_OCP if (isSupported): sample_groupType_CV_list = SampleGroupType_CV.objects.all().order_by("displayedName") else: sample_groupType_CV_list = SampleGroupType_CV.objects.all().exclude(displayedName="DNA_RNA").order_by("displayedName") return sample_groupType_CV_list def _get_sampleSet_list(request): """ Returns a list of sample sets to which we can still add samples """ sampleSet_list = None isSupported = GlobalConfig.get().enable_compendia_OCP if (isSupported): sampleSet_list = SampleSet.objects.all().order_by("-lastModifiedDate", "displayedName") else: sampleSet_list = SampleSet.objects.all().exclude(SampleGroupType_CV__displayedName="DNA_RNA").order_by("-lastModifiedDate", "displayedName") # exclude sample sets that are of amps_on_chef_v1 AND already have 8 samples annotated_list = sampleSet_list.exclude(status__in=["voided", "libPrep_reserved"]).annotate(Count("samples")) exclude_id_list = annotated_list.values_list("id", flat=True).filter(libraryPrepType="amps_on_chef_v1", samples__count=8) available_sampleSet_list = annotated_list.exclude(pk__in=exclude_id_list) logger.debug("_get_sampleSet_list() sampleSet_list.count=%d; available_sampleSet_list=%d" % (annotated_list.count(), available_sampleSet_list.count())) return available_sampleSet_list def _get_all_userTemplates(request): isSupported = GlobalConfig.get().enable_compendia_OCP all_templates = None if isSupported: all_templates = PlannedExperiment.objects.filter(isReusable=True, isSystem=False).order_by('applicationGroup', 'sampleGrouping', '-date', 'planDisplayedName') else: all_templates = PlannedExperiment.objects.filter(isReusable=True, isSystem=False).exclude(sampleGrouping__displayedName="DNA_RNA").order_by('applicationGroup', 'sampleGrouping', '-date', 'planDisplayedName') return all_templates def _get_all_systemTemplates(request): isSupported = GlobalConfig.get().enable_compendia_OCP all_templates = None if isSupported: all_templates = PlannedExperiment.objects.filter(isReusable=True, isSystem=True, isSystemDefault=False).order_by('applicationGroup', 'sampleGrouping', 'planDisplayedName') else: all_templates = PlannedExperiment.objects.filter(isReusable=True, isSystem=True, isSystemDefault=False).exclude(sampleGrouping__displayedName="DNA_RNA").order_by('applicationGroup', 'sampleGrouping', 'planDisplayedName') return all_templates @login_required def show_samplesets(request): """ show the sample sets home page """ ctxd = {} # custom_sample_column_objs = SampleAttribute.objects.filter(isActive = True).order_by('id') custom_sample_column_list = list(SampleAttribute.objects.filter(isActive=True).values_list('displayedName', flat=True).order_by('id')) # custom_sample_column_list = SampleAttribute.objects.filter(isActive = True).order_by('id') sample_groupType_CV_list = _get_sample_groupType_CV_list(request) sample_role_CV_list = SampleAnnotation_CV.objects.filter(annotationType="relationshipRole").order_by('value') ctxd = { # 'custom_sample_column_objs' : custom_sample_column_objs, 'custom_sample_column_list': simplejson.dumps(custom_sample_column_list), # 'custom_sample_column_list' : custom_sample_column_list, 'sample_groupType_CV_list': sample_groupType_CV_list, 'sample_role_CV_list': sample_role_CV_list } ctx = RequestContext(request, ctxd) return render_to_response("rundb/sample/samplesets.html", context_instance=ctx, mimetype="text/html") @login_required def show_sample_attributes(request): """ show the user-defined sample attribute home page """ ctxd = {} ctx = RequestContext(request, ctxd) return render_to_response("rundb/sample/sampleattributes.html", context_instance=ctx, mimetype="text/html") @login_required def download_samplefile_format(request): """ download sample file format """ response = http.HttpResponse(mimetype='text/csv') now = str(datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")) response['Content-Disposition'] = 'attachment; filename=sample_file_format_%s.csv' % now sample_csv_version = import_sample_processor.get_sample_csv_version() hdr = [import_sample_processor.COLUMN_SAMPLE_NAME, import_sample_processor.COLUMN_SAMPLE_EXT_ID, import_sample_processor.COLUMN_CONTROLTYPE, import_sample_processor.COLUMN_PCR_PLATE_POSITION, import_sample_processor.COLUMN_BARCODE_KIT, import_sample_processor.COLUMN_BARCODE, import_sample_processor.COLUMN_GENDER, import_sample_processor.COLUMN_GROUP_TYPE, import_sample_processor.COLUMN_GROUP, import_sample_processor.COLUMN_SAMPLE_DESCRIPTION, import_sample_processor.COLUMN_NUCLEOTIDE_TYPE, import_sample_processor.COLUMN_CANCER_TYPE, import_sample_processor.COLUMN_CELLULARITY_PCT, import_sample_processor.COLUMN_BIOPSY_DAYS, import_sample_processor.COLUMN_CELL_NUM, import_sample_processor.COLUMN_COUPLE_ID, import_sample_processor.COLUMN_EMBRYO_ID ] customAttributes = SampleAttribute.objects.all().exclude(isActive=False).order_by("displayedName") for customAttribute in customAttributes: hdr.append(customAttribute) writer = csv.writer(response) writer.writerow(sample_csv_version) writer.writerow(hdr) return response @login_required def show_import_samplesetitems(request): """ show the page to import samples from file for sample set creation """ ctxd = {} sampleSet_list = _get_sampleSet_list(request) sampleGroupType_list = list(_get_sample_groupType_CV_list(request)) libraryPrepType_choices = views_helper._get_libraryPrepType_choices(request) libraryPrepKits = KitInfo.objects.filter(kitType='LibraryPrepKit', isActive=True) ctxd = { 'sampleSet_list': sampleSet_list, 'sampleGroupType_list': sampleGroupType_list, 'libraryPrepType_choices': libraryPrepType_choices, 'libraryPrepKits': libraryPrepKits, } ctx = RequestContext(request, ctxd) return render_to_response("rundb/sample/import_samples.html", context_instance=ctx, mimetype="text/html") @login_required def show_edit_sampleset(request, _id=None): """ show the sample set add/edit page """ ctxd = {} if _id: sampleSet = get_object_or_404(SampleSet, pk=_id) intent = "edit" editable = sampleSet.status in ['', 'created', 'libPrep_pending'] else: sampleSet = None intent = "add" editable = True sampleGroupType_list = _get_sample_groupType_CV_list(request) libraryPrepType_choices = views_helper._get_libraryPrepType_choices(request) if editable: libraryPrepKits = KitInfo.objects.filter(kitType='LibraryPrepKit', isActive=True) else: libraryPrepKits = KitInfo.objects.filter(name=sampleSet.libraryPrepKitName) ctxd = { 'sampleSet': sampleSet, 'sampleGroupType_list': sampleGroupType_list, 'libraryPrepType_choices': libraryPrepType_choices, 'libraryPrepKits': libraryPrepKits, 'intent': intent, 'editable': editable } ctx = RequestContext(request, ctxd) return render_to_response("rundb/sample/modal_add_sampleset.html", context_instance=ctx, mimetype="text/html") @login_required def show_plan_run(request, ids): """ show the plan run popup """ warnings = [] sampleset_ids = ids.split(',') sampleSets = SampleSet.objects.filter(pk__in=sampleset_ids) if len(sampleSets) < 1: raise http.Http404("SampleSet not found") # validate errors = sample_validator.validate_sampleSets_for_planning(sampleSets) if errors: msg = "Cannot Plan Run from %s<br>" % ', '.join(sampleSets.values_list('displayedName', flat=True)) return http.HttpResponseServerError(msg + '<br>'.join(errors)) # multiple sample group types are allowed, with a warning sampleGroupTypes = sampleSets.filter(SampleGroupType_CV__isnull=False).values_list('SampleGroupType_CV__displayedName', flat=True).distinct() if len(sampleGroupTypes) > 1: warnings.append('Warning: multiple Group Types selected: %s' % ', '.join(sampleGroupTypes)) all_templates = _get_all_userTemplates(request) all_templates_params = list(all_templates.values('pk', 'planDisplayedName', 'sampleGrouping__displayedName')) # we want to display the system templates last all_systemTemplates = _get_all_systemTemplates(request) all_systemTemplates_params = list(all_systemTemplates.values('pk', 'planDisplayedName', 'sampleGrouping__displayedName')) ctxd = { 'sampleSet_ids': ids, 'sampleGroupTypes': sampleGroupTypes, 'template_params': all_templates_params + all_systemTemplates_params, 'warnings': warnings, } ctx = RequestContext(request, ctxd) return render_to_response("rundb/sample/modal_plan_run.html", context_instance=ctx, mimetype="text/html") @login_required def save_sampleset(request): """ create or edit a new sample set (with no contents) """ if request.method == "POST": intent = request.POST.get('intent', None) # TODO: validation (including checking the status again!! queryDict = request.POST isValid, errorMessage = sample_validator.validate_sampleSet(queryDict); if errorMessage: # return HttpResponse(errorMessage, mimetype="text/html") return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") if isValid: userName = request.user.username user = User.objects.get(username=userName) logger.debug("views.save_sampleset POST save_sampleset queryDict=%s" % (queryDict)) # logger.debug("save_sampleset sampleSetName=%s" %(queryDict.get("sampleSetName", ""))) # logger.debug("save_sampleset sampleSetDesc=%s" %(queryDict.get("sampleSetDescription", ""))) # logger.debug("save_sampleset_sampleSet_groupType=%s" %(queryDict.get("groupType", None))) # logger.debug("save_sampleset id=%s" %(queryDict.get("id", None))) sampleSetName = queryDict.get("sampleSetName", "").strip() sampleSetDesc = queryDict.get("sampleSetDescription", "").strip() sampleSet_groupType_id = queryDict.get("groupType", None) if sampleSet_groupType_id == "0": sampleSet_groupType_id = None libraryPrepType = queryDict.get("libraryPrepType", "").strip() if libraryPrepType and "chef" in libraryPrepType.lower(): libraryPrepInstrument = "chef" else: libraryPrepInstrument = "" libraryPrepKitName = queryDict.get("libraryPrepKit", "").strip() pcrPlateSerialNum = queryDict.get("pcrPlateSerialNum", "").strip() sampleSet_id = queryDict.get("id", None) currentDateTime = timezone.now() #datetime.datetime.now() try: if intent == "add": sampleSetStatus = "created" if sampleSet.libraryPrepInstrument == "chef": libraryPrepInstrumentData_obj = models.SamplePrepData.objects.create(samplePrepDataType="lib_prep") sampleSetStatus = "libPrep_pending" else: libraryPrepInstrumentData_obj = None sampleSet_kwargs = { 'displayedName': sampleSetName, 'description': sampleSetDesc, 'status': sampleSetStatus, 'SampleGroupType_CV_id': sampleSet_groupType_id, 'libraryPrepType': libraryPrepType, 'libraryPrepKitName': libraryPrepKitName, 'pcrPlateSerialNum': pcrPlateSerialNum, 'libraryPrepInstrument': libraryPrepInstrument, 'libraryPrepInstrumentData': libraryPrepInstrumentData_obj, 'creator': user, 'creationDate': currentDateTime, 'lastModifiedUser': user, 'lastModifiedDate': currentDateTime } sampleSet = SampleSet(**sampleSet_kwargs) sampleSet.save() logger.debug("views - save_sampleset - ADDED sampleSet.id=%d" % (sampleSet.id)) else: orig_sampleSet = get_object_or_404(SampleSet, pk=sampleSet_id) if (orig_sampleSet.displayedName == sampleSetName and orig_sampleSet.description == sampleSetDesc and orig_sampleSet.SampleGroupType_CV and str(orig_sampleSet.SampleGroupType_CV.id) == sampleSet_groupType_id and orig_sampleSet.libraryPrepType == libraryPrepType and orig_sampleSet.libraryPrepKitName == libraryPrepKitName and orig_sampleSet.pcrPlateSerialNum == pcrPlateSerialNum): logger.debug("views.save_sampleset() - NO UPDATE NEEDED!! sampleSet.id=%d" % (orig_sampleSet.id)) else: sampleSetStatus = orig_sampleSet.status libraryPrepInstrumentData_obj = orig_sampleSet.libraryPrepInstrumentData # clean up the associated object if the sample set used to be "amps_on_chef" and now is not if libraryPrepInstrumentData_obj and not libraryPrepType: logger.debug("views - GOING TO DELETE orig_sampleSet orig_sampleSet.libraryPrepInstrumentData.id=%d" % (orig_sampleSet.libraryPrepInstrumentData.id)) libraryPrepInstrumentData_obj.delete() if sampleSetStatus == "libPrep_pending": sampleSetStatus = "created" elif libraryPrepType and not libraryPrepInstrumentData_obj: libraryPrepInstrumentData_obj = SamplePrepData.objects.create(samplePrepDataType="lib_prep") logger.debug("views - orig_sampleSet.id=%d; GOING TO ADD libraryPrepInstrumentData_obj.id=%d" % (orig_sampleSet.id, libraryPrepInstrumentData_obj.id)) if sampleSetStatus == "created": sampleSetStatus = "libPrep_pending" sampleSet_kwargs = { 'displayedName': sampleSetName, 'description': sampleSetDesc, 'SampleGroupType_CV_id': sampleSet_groupType_id, 'libraryPrepType': libraryPrepType, 'libraryPrepKitName': libraryPrepKitName, 'pcrPlateSerialNum': pcrPlateSerialNum, 'libraryPrepInstrument': libraryPrepInstrument, 'libraryPrepInstrumentData': libraryPrepInstrumentData_obj, 'status': sampleSetStatus, 'lastModifiedUser': user, 'lastModifiedDate': currentDateTime } for field, value in sampleSet_kwargs.iteritems(): setattr(orig_sampleSet, field, value) orig_sampleSet.save() logger.debug("views.save_sampleset - UPDATED sampleSet.id=%d" % (orig_sampleSet.id)) return HttpResponse("true") except: logger.exception(format_exc()) # return HttpResponse(json.dumps({"status": "Error saving sample set info to database!"}), mimetype="text/html") message = "Cannot save sample set to database. " if settings.DEBUG: message += format_exc() return HttpResponse(json.dumps([message]), mimetype="application/json") else: return HttpResponse(json.dumps(["Error, Cannot save sample set due to validation errors."]), mimetype="application/json") else: return HttpResponseRedirect("/sample/") @login_required @transaction.commit_manually def save_samplesetitem(request): """ create or edit a new sample set item """ if request.method == "POST": intent = request.POST.get('intent', None) logger.debug("at views.save_samplesetitem() intent=%s" % (intent)) # json_data = simplejson.loads(request.body) raw_data = request.body logger.debug('views.save_samplesetitem POST.body... body: "%s"' % raw_data) logger.debug('views.save_samplesetitem request.session: "%s"' % request.session) # TODO: validation (including checking the status) queryDict = request.POST isValid, errorMessage = sample_validator.validate_sample_for_sampleSet(queryDict) if errorMessage: # return HttpResponse(errorMessage, mimetype="text/html") transaction.rollback() return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") logger.debug("views.save_samplesetitem() B4 validate_barcoding queryDict=%s" % (queryDict)) isValid, errorMessage = sample_validator.validate_sample_pgx_attributes_for_sampleSet(queryDict) if errorMessage: transaction.rollback() return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") try: isValid, errorMessage = sample_validator.validate_barcoding(request, queryDict) except: logger.exception(format_exc()) transaction.rollback() return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") if errorMessage: transaction.rollback() return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") try: sampleSetItemDescription = queryDict.get("sampleDescription", "").strip() isValid, errorMessage = sample_validator.validate_sampleDescription(sampleSetItemDescription) except: logger.exception(format_exc()) transaction.rollback() return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") if errorMessage: transaction.rollback() return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") try: isValid, errorMessage = sample_validator.validate_pcrPlate_position(request, queryDict) except: logger.exception(format_exc()) transaction.rollback() return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") if errorMessage: transaction.rollback() return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") if isValid: userName = request.user.username user = User.objects.get(username=userName) currentDateTime = timezone.now() ##datetime.datetime.now() logger.info("POST save_samplesetitem queryDict=%s" % (queryDict)) sampleSetItem_id = queryDict.get("id", None) new_sample = None try: if intent == "add": logger.info("views.save_samplesetitem - TODO!!! - unsupported for now") elif intent == "edit": new_sample = views_helper._create_or_update_sample_for_sampleSetItem(request, user) isValid, errorMessage = views_helper._create_or_update_sampleAttributes_for_sampleSetItem(request, user, new_sample) if not isValid: transaction.rollback() # return HttpResponse(errorMessage, mimetype="text/html") return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") isValid, errorMessage = views_helper._create_or_update_sampleSetItem(request, user, new_sample) if not isValid: transaction.rollback() # return HttpResponse(errorMessage, mimetype="text/html") return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") elif intent == "add_pending": isValid, errorMessage, pending_sampleSetItem = views_helper._create_pending_sampleSetItem_dict(request, userName, currentDateTime) if errorMessage: transaction.rollback() # return HttpResponse(errorMessage, mimetype="text/html") return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") views_helper._update_input_samples_session_context(request, pending_sampleSetItem) transaction.commit() return HttpResponse("true") elif intent == "edit_pending": isValid, errorMessage, pending_sampleSetItem = views_helper._update_pending_sampleSetItem_dict(request, userName, currentDateTime) if errorMessage: transaction.rollback() # return HttpResponse(errorMessage, mimetype="text/html") return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") views_helper._update_input_samples_session_context(request, pending_sampleSetItem, False) transaction.commit() return HttpResponse("true") transaction.commit() return HttpResponse("true") except: logger.exception(format_exc()) transaction.rollback() # return HttpResponse(json.dumps({"status": "Error saving sample set info to database!"}), mimetype="text/html") message = "Cannot save sample changes. " if settings.DEBUG: message += format_exc() return HttpResponse(json.dumps([message]), mimetype="application/json") else: # errors = form._errors.setdefault(forms.forms.NON_FIELD_ERRORS, forms.util.ErrorList()) # return HttpResponse(errors) logger.info("views.save_samplesetitem - INVALID - FAILED!!") transaction.rollback() # return HttpResponse(json.dumps({"status": "Could not save sample set due to validation errors"}), mimetype="text/html") return HttpResponse(json.dumps(["Cannot save sample changes due to validation errors."]), mimetype="application/json") else: return HttpResponseRedirect("/sample/") @login_required @transaction.commit_manually def save_input_samples_for_sampleset(request): """ create a new sample set item with manually entered samples """ if request.method == "POST": # json_data = simplejson.loads(request.body) raw_data = request.body logger.debug('views.save_input_samples_for_sampleset POST.body... body: "%s"' % raw_data) logger.debug('views.save_input_samples_for_sampleset request.session: "%s"' % request.session) # TODO: validation # logic: # 1) if no input samples, nothing to do # 2) validate input samples # 3) validate input sample set # 4) validate sample does not exist inside the sample set yet # 5) if valid, get or create sample sets # 6) for each input sample, # 6.a) create or update sample # 6.b) create or update sample attributes # 6.c) create or update sample set item if "input_samples" not in request.session: transaction.rollback() return HttpResponse(json.dumps(["No manually entered samples found to create a sample set."]), mimetype="application/json") userName = request.user.username user = User.objects.get(username=userName) currentDateTime = timezone.now() ##datetime.datetime.now() queryDict = request.POST logger.info("POST save_input_samples_for_sampleset queryDict=%s" % (queryDict)) # 1) get or create sample sets try: # create sampleSets only if we have at least one good sample to process isValid, errorMessage, sampleSet_ids = views_helper._get_or_create_sampleSets(request, user) if not isValid: transaction.rollback() # return HttpResponse(errorMessage, mimetype="text/html") return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") isValid, errorMessage = views_helper.validate_for_existing_samples(request, sampleSet_ids) if not isValid: transaction.rollback() # return HttpResponse(errorMessage, mimetype="text/html") return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") if not sampleSet_ids: transaction.rollback() return HttpResponse(json.dumps(["Error, Please select a sample set or add a new sample set first."]), mimetype="application/json") # a list of dictionaries pending_sampleSetItem_list = request.session['input_samples']['pending_sampleSetItem_list'] for pending_sampleSetItem in pending_sampleSetItem_list: sampleDisplayedName = pending_sampleSetItem.get("displayedName", "").strip() sampleExternalId = pending_sampleSetItem.get("externalId", "").strip() sampleDesc = pending_sampleSetItem.get("description", "").strip() sampleControlType = pending_sampleSetItem.get("controlType", "") sampleAttribute_dict = pending_sampleSetItem.get("attribute_dict") or {} sampleGender = pending_sampleSetItem .get("gender", "") sampleRelationshipRole = pending_sampleSetItem.get("relationshipRole", "") sampleRelationshipGroup = pending_sampleSetItem.get("relationshipGroup", "") sampleCancerType = pending_sampleSetItem.get("cancerType", "") sampleCellularityPct = pending_sampleSetItem.get("cellularityPct", None) if sampleCellularityPct == "": sampleCellularityPct = None selectedBarcodeKit = pending_sampleSetItem.get("barcodeKit", "") selectedBarcode = pending_sampleSetItem.get("barcode", "") sampleNucleotideType = pending_sampleSetItem.get("nucleotideType", "") pcrPlateRow = pending_sampleSetItem.get("pcrPlateRow", "") sampleBiopsyDays = pending_sampleSetItem.get("biopsyDays", "0") if not sampleBiopsyDays: sampleBiopsyDays = "0" sampleCellNum = pending_sampleSetItem.get("cellNum", "") sampleCoupleId = pending_sampleSetItem.get("coupleId", "") sampleEmbryoId = pending_sampleSetItem.get("embryoId", "") new_sample = views_helper._create_or_update_sample_for_sampleSetItem_with_values(request, user, sampleDisplayedName, sampleExternalId, sampleDesc, selectedBarcodeKit, selectedBarcode) isValid, errorMessage = views_helper._create_or_update_sampleAttributes_for_sampleSetItem_with_dict(request, user, new_sample, sampleAttribute_dict) if not isValid: transaction.rollback() # return HttpResponse(errorMessage, mimetype="text/html") return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") views_helper._create_or_update_pending_sampleSetItem(request, user, sampleSet_ids, new_sample, sampleGender, sampleRelationshipRole, sampleRelationshipGroup, sampleControlType,\ selectedBarcodeKit, selectedBarcode, sampleCancerType, sampleCellularityPct, sampleNucleotideType, pcrPlateRow, sampleBiopsyDays, sampleCellNum, sampleCoupleId, sampleEmbryoId, sampleDesc) clear_samplesetitem_session(request) transaction.commit() return HttpResponse("true") except: logger.exception(format_exc()) transaction.rollback() # return HttpResponse(json.dumps({"status": "Error saving manually entered sample set info to database. " + format_exc()}), mimetype="text/html") errorMessage = "Error saving manually entered sample set info to database. " if settings.DEBUG: errorMessage += format_exc() return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") else: return HttpResponseRedirect("/sample/") @login_required def clear_input_samples_for_sampleset(request): clear_samplesetitem_session(request) return HttpResponseRedirect("/sample/samplesetitem/input/") @login_required def get_input_samples_data(request): data = {} data["meta"] = {} data["meta"]["total_count"] = views_helper._get_pending_sampleSetItem_count(request) data["objects"] = request.session['input_samples']['pending_sampleSetItem_list'] json_data = json.dumps(data) logger.debug("views.get_input_samples_data json_data=%s" % (json_data)) return HttpResponse(json_data, mimetype='application/json') # return HttpResponse(json_data, mimetype="text/html") @login_required @transaction.commit_manually def save_import_samplesetitems(request): """ save the imported samples from file for sample set creation """ logger.info(request) if request.method != 'POST': logger.exception(format_exc()) transaction.rollback() return HttpResponse(json.dumps({"error": "Error, unsupported HTTP Request method (%s) for saving sample upload." % request.method}), mimetype="application/json") postedfile = request.FILES['postedfile'] destination = tempfile.NamedTemporaryFile(delete=False) for chunk in postedfile.chunks(): destination.write(chunk) postedfile.close() destination.close() # check to ensure it is not empty headerCheck = open(destination.name, "rU") firstCSV = [] for firstRow in csv.reader(headerCheck): firstCSV.append(firstRow) # logger.info("views.save_import_samplesetitems() firstRow=%s;" %(firstRow)) headerCheck.close() if not firstRow: os.unlink(destination.name) transaction.rollback() return HttpResponse(json.dumps({"status": "Error: sample file is empty"}), mimetype="text/html") index = 0 row_count = 0 errorMsg = [] samples = [] rawSampleDataList = [] failed = {} file = open(destination.name, "rU") csv_version_row = csv.reader(file).next() # skip the csv template version header and proceed reader = csv.DictReader(file) userName = request.user.username user = User.objects.get(username=userName) # Validate the sample CSV template version csv_version_header = import_sample_processor.get_sample_csv_version()[0] errorMsg, isToSkipRow, isToAbort = utils.validate_csv_template_version(headerName=csv_version_header, isSampleCSV=True, firstRow=csv_version_row) if isToAbort: csv_version_index = 1 failed[csv_version_index] = errorMsg r = {"status": ERROR_MSG_SAMPLE_IMPORT_VALIDATION, "failed": failed} logger.info("views.save_import_samples_for_sampleset() failed=%s" % (r)) transaction.rollback() return HttpResponse(json.dumps(r), mimetype="text/html") try: for index, row in enumerate(reader, start=2): logger.debug("LOOP views.save_import_samples_for_sampleset() validate_csv_sample...index=%d; row=%s" % (index, row)) errorMsg, isToSkipRow, isToAbort = import_sample_processor.validate_csv_sample(row, request) if errorMsg: if isToAbort: failed["File"] = errorMsg else: failed[index] = errorMsg elif isToSkipRow: logger.debug("views.save_import_samples_for_sampleset() SKIPPED ROW index=%d; row=%s" % (index, row)) continue else: rawSampleDataList.append(row) row_count += 1 if isToAbort: r = {"status": ERROR_MSG_SAMPLE_IMPORT_VALIDATION, "failed": failed} logger.info("views.save_import_samples_for_sampleset() failed=%s" % (r)) transaction.rollback() return HttpResponse(json.dumps(r), mimetype="text/html") # now validate that all barcode kit are the same and that each combo of barcode kit and barcode id_str is unique errorMsg = import_sample_processor.validate_barcodes_are_unique(rawSampleDataList) if errorMsg: for k, v in errorMsg.items(): failed[k] = [v] # return HttpResponse(json.dumps({"status": ERROR_MSG_SAMPLE_IMPORT_VALIDATION, "failed" : {"Sample Set" : [errorMessage]}}), mimetype="text/html") errorMsg = import_sample_processor.validate_pcrPlateRow_are_unique(rawSampleDataList) if errorMsg: for k, v in errorMsg.items(): failed[k] = [v] logger.info("views.save_import_samples_for_sampleset() row_count=%d" % (row_count)) destination.close() # now close and remove the temp file os.unlink(destination.name) except: logger.exception(format_exc()) transaction.rollback() message = "Error saving sample set info to database. " if settings.DEBUG: message += format_exc() return HttpResponse(json.dumps({"status": message}), mimetype="text/html") if failed: r = {"status": ERROR_MSG_SAMPLE_IMPORT_VALIDATION, "failed": failed} logger.info("views.save_import_samples_for_sampleset() failed=%s" % (r)) transaction.rollback() return HttpResponse(json.dumps(r), mimetype="text/html") if row_count > 0: try: # validate new sampleSet entry before proceeding further isValid, errorMessage, sampleSet_ids = views_helper._get_or_create_sampleSets(request, user) if not isValid: msgList = [] msgList.append(errorMessage) failed["Sample Set"] = msgList r = {"status": ERROR_MSG_SAMPLE_IMPORT_VALIDATION, "failed": failed} logger.info("views.save_import_samples_for_sampleset() failed=%s" % (r)) transaction.rollback() return HttpResponse(json.dumps(r), mimetype="text/html") errorMsg = import_sample_processor.validate_barcodes_for_existing_samples(rawSampleDataList, sampleSet_ids) if errorMsg: for k, v in errorMsg.items(): failed[k] = [v] errorMsg = import_sample_processor.validate_pcrPlateRow_for_existing_samples(rawSampleDataList, sampleSet_ids) if errorMsg: for k, v in errorMsg.items(): failed[k] = [v] if len(sampleSet_ids) == 0: msgList = [] msgList.append("Error: There must be at least one valid sample set. Please select or input a sample set. ") failed["Sample Set"] = msgList r = {"status": ERROR_MSG_SAMPLE_IMPORT_VALIDATION, "failed": failed} transaction.rollback() return HttpResponse(json.dumps(r), mimetype="text/html") if (index > 0): index_process = index for sampleData in rawSampleDataList: index_process += 1 logger.debug("LOOP views.save_import_samples_for_sampleset() process_csv_sampleSet...index_process=%d; sampleData=%s" % (index_process, sampleData)) errorMsg, sample, sampleSetItem, isToSkipRow, ssi_sid, siv_sid = import_sample_processor.process_csv_sampleSet(sampleData, request, user, sampleSet_ids) if errorMsg: failed[index_process] = errorMsg except: logger.exception(format_exc()) transaction.rollback() message = "Error saving sample set info to database. " if settings.DEBUG: message += format_exc() return HttpResponse(json.dumps({"status": message}), mimetype="text/html") if failed: r = {"status": "Error: Sample set validation failed. The sample set info has not been saved.", "failed": failed} logger.info("views.save_import_samples_for_sampleset() failed=%s" % (r)) transaction.rollback() return HttpResponse(json.dumps(r), mimetype="text/html") else: transaction.commit() r = {"status": "Samples Uploaded! The sample set will be listed on the sample set page.", "failed": failed} return HttpResponse(json.dumps(r), mimetype="text/html") else: logger.debug("EXITING views.save_import_samples_for_sampleset() row_count=%d" % (row_count)) transaction.rollback() return HttpResponse(json.dumps({"status": "Error: There must be at least one valid sample. Please correct the errors or import another sample file."}), mimetype="text/html") @login_required def show_input_samplesetitems(request): """ show the page to allow user to input samples for sample set creation """ ctx = views_helper._handle_enter_samples_manually_request(request) return render_to_response("rundb/sample/input_samples.html", context_instance=ctx, mimetype="text/html") def
(request, intent, sampleSetItem=None, pending_sampleSetItem=None): sample_groupType_CV_list = _get_sample_groupType_CV_list(request) sample_role_CV_list = SampleAnnotation_CV.objects.filter(isActive=True, annotationType="relationshipRole").order_by('value') controlType_CV_list = SampleAnnotation_CV.objects.filter(isActive=True, annotationType="controlType").order_by('value') gender_CV_list = SampleAnnotation_CV.objects.filter(isActive=True, annotationType="gender").order_by('value') cancerType_CV_list = SampleAnnotation_CV.objects.filter(isActive=True, annotationType="cancerType").order_by('value') sampleAttribute_list = SampleAttribute.objects.filter(isActive=True).order_by('id') sampleAttributeValue_list = [] selectedBarcodeKit = None sampleGroupTypeName = "" pcrPlateRow_choices = views_helper._get_pcrPlateRow_choices(request) if intent == "edit": selectedGroupType = sampleSetItem.sampleSet.SampleGroupType_CV if selectedGroupType: # if sample grouping is selected, try to limit to whatever relationship roles are compatible. But if none is compatible, include all filtered_sample_role_CV_list = SampleAnnotation_CV.objects.filter(sampleGroupType_CV=selectedGroupType, annotationType="relationshipRole").order_by('value') if filtered_sample_role_CV_list: sample_role_CV_list = filtered_sample_role_CV_list sampleGroupTypeName = selectedGroupType.displayedName if sampleSetItem.nucleotideType == "rna" and "Fusions" in selectedGroupType.displayedName: sampleSetItem.nucleotideType = "fusions" sampleAttributeValue_list = SampleAttributeValue.objects.filter(sample_id=sampleSetItem.sample) selectedBarcodeKit = sampleSetItem.dnabarcode.name if sampleSetItem.dnabarcode else None available_dnaBarcodes = dnaBarcode.objects.filter(Q(active=True) | Q(name=selectedBarcodeKit)) barcodeKits = list(available_dnaBarcodes.values('name').distinct().order_by('name')) barcodeInfo = list(available_dnaBarcodes.order_by('name', 'index')) nucleotideType_choices = views_helper._get_nucleotideType_choices(sampleGroupTypeName) ctxd = { 'sampleSetItem': sampleSetItem, 'pending_sampleSetItem': pending_sampleSetItem, 'sample_groupType_CV_list': sample_groupType_CV_list, 'sample_role_CV_list': sample_role_CV_list, 'controlType_CV_list': controlType_CV_list, 'gender_CV_list': gender_CV_list, 'cancerType_CV_list': cancerType_CV_list, 'sampleAttribute_list': sampleAttribute_list, 'sampleAttributeValue_list': sampleAttributeValue_list, 'barcodeKits': barcodeKits, 'barcodeInfo': barcodeInfo, 'nucleotideType_choices': nucleotideType_choices, 'pcrPlateRow_choices': pcrPlateRow_choices, 'intent': intent } ctx = RequestContext(request, ctxd) return render_to_response("rundb/sample/modal_add_samplesetitem.html", context_instance=ctx, mimetype="text/html") def show_add_pending_samplesetitem(request): """ show the sample set input page """ return show_samplesetitem_modal(request, "add_pending") @login_required def show_edit_pending_samplesetitem(request, pending_sampleSetItemId): """ show the sample set edit page """ logger.debug("views.show_edit_pending_samplesetitem pending_sampleSetItemId=%s; " % (str(pending_sampleSetItemId))) pending_sampleSetItem = views_helper._get_pending_sampleSetItem_by_id(request, pending_sampleSetItemId) if pending_sampleSetItem is None: msg = "Error, The selected sample is no longer available for this session." return HttpResponse(msg, mimetype="text/html") return show_samplesetitem_modal(request, "edit_pending", pending_sampleSetItem=pending_sampleSetItem) @login_required def remove_pending_samplesetitem(request, _id): """ remove the selected pending sampleSetItem from the session context """ logger.debug("ENTER views.remove_pending_samplesetitem() id=%s" % (str(_id))) if "input_samples" in request.session: items = request.session["input_samples"]["pending_sampleSetItem_list"] index = 0 for item in items: if (item.get("pending_id", -99) == int(_id)): # logger.debug("FOUND views.delete_pending_samplesetitem() id=%s; index=%d" %(str(_id), index)) del request.session["input_samples"]["pending_sampleSetItem_list"][index] request.session.modified = True return HttpResponseRedirect("/sample/samplesetitem/input/") else: index += 1 logger.debug("views_helper._update_input_samples_session_context AFTER REMOVE session_contents=%s" % (request.session["input_samples"])) return HttpResponseRedirect("/sample/samplesetitem/input/") @login_required def show_save_input_samples_for_sampleset(request): """ show the page to allow user to assign input samples to a sample set and trigger save """ ctxd = {} sampleSet_list = _get_sampleSet_list(request) sampleGroupType_list = list(_get_sample_groupType_CV_list(request)) libraryPrepType_choices = views_helper._get_libraryPrepType_choices(request) libraryPrepKits = KitInfo.objects.filter(kitType='LibraryPrepKit', isActive=True) ctxd = { 'sampleSet_list': sampleSet_list, 'sampleGroupType_list': sampleGroupType_list, 'libraryPrepType_choices': libraryPrepType_choices, 'libraryPrepKits': libraryPrepKits, } ctx = RequestContext(request, ctxd) return render_to_response("rundb/sample/modal_save_samplesetitems.html", context_instance=ctx, mimetype="text/html") @login_required def show_add_sample_attribute(request): """ show the page to add a custom sample attribute """ ctxd = {} attr_type_list = SampleAttributeDataType.objects.filter(isActive=True).order_by("dataType") ctxd = { 'sample_attribute': None, 'attribute_type_list': attr_type_list, 'intent': "add" } ctx = RequestContext(request, ctxd) return render_to_response("rundb/sample/modal_add_sample_attribute.html", context_instance=ctx, mimetype="text/html") @login_required def show_edit_sample_attribute(request, _id): """ show the page to edit a custom sample attribute """ ctxd = {} sample_attribute = get_object_or_404(SampleAttribute, pk=_id) attr_type_list = SampleAttributeDataType.objects.filter(isActive=True).order_by("dataType") ctxd = { 'sample_attribute': sample_attribute, 'attribute_type_list': attr_type_list, 'intent': "edit" } ctx = RequestContext(request, ctxd) return render_to_response("rundb/sample/modal_add_sample_attribute.html", context_instance=ctx, mimetype="text/html") @login_required def toggle_visibility_sample_attribute(request, _id): """ show or hide a custom sample attribute """ ctxd = {} sample_attribute = get_object_or_404(SampleAttribute, pk=_id) toggle_showHide = False if (sample_attribute.isActive) else True sample_attribute.isActive = toggle_showHide userName = request.user.username user = User.objects.get(username=userName) currentDateTime = timezone.now() ##datetime.datetime.now() sample_attribute.lastModifiedUser = user sample_attribute.lastModifiedDate = currentDateTime sample_attribute.save() return HttpResponseRedirect("/sample/sampleattribute/") @login_required def delete_sample_attribute(request, _id): """ delete the selected custom sample attribute """ _type = 'sampleattribute' sampleAttribute = get_object_or_404(SampleAttribute, pk=_id) sampleValue_count = sampleAttribute.samples.count() _typeDescription = "Sample Attribute and " + str(sampleValue_count) + " related Sample Attribute Value(s)" if sampleValue_count > 0 else "Sample Attribute" ctx = RequestContext(request, { "id": _id, "ids": json.dumps([_id]), "names": sampleAttribute.displayedName, "method": "DELETE", 'methodDescription': 'Delete', "readonly": False, 'type': _typeDescription, 'action': reverse('api_dispatch_detail', kwargs={'resource_name': _type, 'api_name': 'v1', 'pk': int(_id)}), 'actions': json.dumps([]) }) return render_to_response("rundb/common/modal_confirm_delete.html", context_instance=ctx) @login_required def delete_sampleset(request, _id): """ delete the selected sample set """ _type = 'sampleset' sampleSet = get_object_or_404(SampleSet, pk=_id) sampleSetItems = SampleSetItem.objects.filter(sampleSet=sampleSet) sample_count = sampleSetItems.count() plans = PlannedExperiment.objects.filter(sampleSets=sampleSet) if plans: planCount = plans.count() msg = "Error, There are %d plans for this sample set. Sample set %s cannot be deleted." % (planCount, sampleSet.displayedName) # return HttpResponse(json.dumps({"error": msg}), mimetype="text/html") return HttpResponse(msg, mimetype="text/html") else: actions = [] actions.append(reverse('api_dispatch_detail', kwargs={'resource_name': _type, 'api_name': 'v1', 'pk': int(_id)})) # need to delete placeholder samplePrepData if any instrumentData_pk = None if sampleSet.libraryPrepInstrumentData: instrumentData_pk = sampleSet.libraryPrepInstrumentData.pk instrumentData_resource = "sampleprepdata" actions.append(reverse('api_dispatch_detail', kwargs={'resource_name': instrumentData_resource, 'api_name': 'v1', 'pk': int(instrumentData_pk)})) _typeDescription = "Sample Set and " + str(sample_count) + " related Sample Association(s)" if sample_count > 0 else "Sample Set" ctx = RequestContext(request, { "id": _id, "ids": json.dumps([_id, int(instrumentData_pk)]) if instrumentData_pk else json.dumps([_id]), "names": sampleSet.displayedName, "method": "DELETE", 'methodDescription': 'Delete', "readonly": False, 'type': _typeDescription, 'action': actions[0], 'actions': json.dumps(actions) }) return render_to_response("rundb/common/modal_confirm_delete.html", context_instance=ctx) @login_required def remove_samplesetitem(request, _id): """ remove the sample associated with the sample set """ _type = 'samplesetitem' sampleSetItem = get_object_or_404(SampleSetItem, pk=_id) # if the sampleset has been run, do not allow sample to be removed sample = sampleSetItem.sample sampleSet = sampleSetItem.sampleSet logger.debug("views.remove_samplesetitem - sampleSetItem.id=%s; name=%s; sampleSet.id=%s" % (str(_id), sample.displayedName, str(sampleSet.id))) plans = PlannedExperiment.objects.filter(sampleSets=sampleSet) if plans: planCount = plans.count() msg = "Error, There are %d plans for this sample set. Sample: %s cannot be removed from the sample set." % (planCount, sample.displayedName) # return HttpResponse(json.dumps({"error": msg}), mimetype="text/html") return HttpResponse(msg, mimetype="text/html") else: _typeDescription = "Sample from the sample set %s" % (sampleSet.displayedName) ctx = RequestContext(request, { "id": _id, "ids": json.dumps([_id]), "names": sample.displayedName, "method": "DELETE", 'methodDescription': 'Remove', "readonly": False, 'type': _typeDescription, 'action': reverse('api_dispatch_detail', kwargs={'resource_name': _type, 'api_name': 'v1', 'pk': int(_id)}), 'actions': json.dumps([]) }) return render_to_response("rundb/common/modal_confirm_delete.html", context_instance=ctx) @login_required def save_sample_attribute(request): """ save sample attribute """ if request.method == 'POST': queryDict = request.POST logger.debug("views.save_sample_attribute POST queryDict=%s; " % (queryDict)) intent = queryDict.get('intent', None) sampleAttribute_id = queryDict.get("id", None) attribute_type_id = queryDict.get('attributeType', None) if attribute_type_id == "0": attribute_type_id = None attribute_name = queryDict.get('sampleAttributeName', None) attribute_description = queryDict.get('attributeDescription', None) if not attribute_name or not attribute_name.strip(): # return HttpResponse(json.dumps({"status": "Error: Attribute name is required"}), mimetype="text/html") return HttpResponse(json.dumps(["Error, Attribute name is required."]), mimetype="application/json") try: sample_attribute_type = SampleAttributeDataType.objects.get(id=attribute_type_id) except: # return HttpResponse(json.dumps({"status": "Error: Attribute type is required"}), mimetype="text/html") return HttpResponse(json.dumps(["Error, Attribute type is required."]), mimetype="application/json") is_mandatory = toBoolean(queryDict.get('is_mandatory', False)) # TODO: validation (including checking the status again!! isValid = True if isValid: try: userName = request.user.username user = User.objects.get(username=userName) currentDateTime = timezone.now() ##datetime.datetime.now() underscored_attribute_name = str(attribute_name.strip().replace(' ', '_')).lower() isValid, errorMessage = sample_validator.validate_sampleAttribute_definition(underscored_attribute_name, attribute_description.strip()) if errorMessage: # return HttpResponse(errorMessage, mimetype="text/html") return HttpResponse(json.dumps([errorMessage]), mimetype="application/json") if intent == "add": new_sample_attribute = SampleAttribute( displayedName=underscored_attribute_name, dataType=sample_attribute_type, description=attribute_description.strip(), isMandatory=is_mandatory, isActive=True, creator=user, creationDate=currentDateTime, lastModifiedUser=user, lastModifiedDate=currentDateTime ) new_sample_attribute.save() else: orig_sampleAttribute = get_object_or_404(SampleAttribute, pk=sampleAttribute_id) if (orig_sampleAttribute.displayedName == underscored_attribute_name and str(orig_sampleAttribute.dataType_id) == attribute_type_id and orig_sampleAttribute.description == attribute_description.strip() and orig_sampleAttribute.isMandatory == is_mandatory): logger.debug("views.save_sample_attribute() - NO UPDATE NEEDED!! sampleAttribute.id=%d" % (orig_sampleAttribute.id)) else: sampleAttribute_kwargs = { 'displayedName': underscored_attribute_name, 'description': attribute_description.strip(), 'dataType_id': attribute_type_id, 'isMandatory': is_mandatory, 'lastModifiedUser': user, 'lastModifiedDate': currentDateTime } for field, value in sampleAttribute_kwargs.iteritems(): setattr(orig_sampleAttribute, field, value) orig_sampleAttribute.save() logger.debug("views.save_sample_attribute - UPDATED sampleAttribute.id=%d" % (orig_sampleAttribute.id)) except: logger.exception(format_exc()) # return HttpResponse(json.dumps({"status": "Error: Cannot save user-defined sample attribute to database"}), mimetype="text/html") message = "Cannot save sample attribute to database. " if settings.DEBUG: message += format_exc() return HttpResponse(json.dumps([message]), mimetype="application/json") return HttpResponse("true") else: # errors = form._errors.setdefault(forms.forms.NON_FIELD_ERRORS, forms.util.ErrorList()) # return HttpResponse(errors) # return HttpResponse(json.dumps({"status": "Could not save sample attribute due to validation errors"}), mimetype="text/html") return HttpResponse(json.dumps(["Cannot save sample attribute due to validation errors."]), mimetype="application/json") else: # return HttpResponse(json.dumps({"status": "Error: Request method to save user-defined sample attribute is invalid"}), mimetype="text/html") return HttpResponse(json.dumps(["Request method for save_sample_attribute is invalid."]), mimetype="application/json") @login_required def show_edit_sample_for_sampleset(request, sampleSetItemId): """ show the sample edit page """ logger.debug("views.show_edit_sample_for_sampleset sampleSetItemId=%s; " % (str(sampleSetItemId))) sampleSetItem = get_object_or_404(SampleSetItem, pk=sampleSetItemId) return show_samplesetitem_modal(request, "edit", sampleSetItem=sampleSetItem) class LibraryPrepDetailView(DetailView): model = SamplePrepData template_name = 'rundb/sample/modal_libraryprep_detail.html' context_object_name = 'data' def library_prep_summary(request, pk): sampleSet = get_object_or_404(SampleSet, pk=pk) if sampleSet.libraryPrepInstrumentData: return LibraryPrepDetailView.as_view()(request, pk=sampleSet.libraryPrepInstrumentData.pk) else: return render_to_response("rundb/sample/modal_libraryprep_detail.html")
show_samplesetitem_modal
lnd_single_hop_invoice_test.go
// +build rpctest package itest import ( "bytes" "context" "time" "github.com/btcsuite/btcutil" "github.com/davecgh/go-spew/spew" "github.com/lightningnetwork/lnd/lnrpc" "github.com/lightningnetwork/lnd/lntest" "github.com/lightningnetwork/lnd/lntest/wait" "github.com/lightningnetwork/lnd/lntypes" "github.com/lightningnetwork/lnd/record" ) func testSingleHopInvoice(net *lntest.NetworkHarness, t *harnessTest)
{ ctxb := context.Background() // Open a channel with 100k satoshis between Alice and Bob with Alice being // the sole funder of the channel. ctxt, _ := context.WithTimeout(ctxb, channelOpenTimeout) chanAmt := btcutil.Amount(100000) chanPoint := openChannelAndAssert( ctxt, t, net, net.Alice, net.Bob, lntest.OpenChannelParams{ Amt: chanAmt, }, ) // Now that the channel is open, create an invoice for Bob which // expects a payment of 1000 satoshis from Alice paid via a particular // preimage. const paymentAmt = 1000 preimage := bytes.Repeat([]byte("A"), 32) invoice := &lnrpc.Invoice{ Memo: "testing", RPreimage: preimage, Value: paymentAmt, } ctxt, _ = context.WithTimeout(ctxt, defaultTimeout) invoiceResp, err := net.Bob.AddInvoice(ctxb, invoice) if err != nil { t.Fatalf("unable to add invoice: %v", err) } // Wait for Alice to recognize and advertise the new channel generated // above. ctxt, _ = context.WithTimeout(ctxb, defaultTimeout) err = net.Alice.WaitForNetworkChannelOpen(ctxt, chanPoint) if err != nil { t.Fatalf("alice didn't advertise channel before "+ "timeout: %v", err) } err = net.Bob.WaitForNetworkChannelOpen(ctxt, chanPoint) if err != nil { t.Fatalf("bob didn't advertise channel before "+ "timeout: %v", err) } // With the invoice for Bob added, send a payment towards Alice paying // to the above generated invoice. sendReq := &lnrpc.SendRequest{ PaymentRequest: invoiceResp.PaymentRequest, } ctxt, _ = context.WithTimeout(ctxb, defaultTimeout) resp, err := net.Alice.SendPaymentSync(ctxt, sendReq) if err != nil { t.Fatalf("unable to send payment: %v", err) } // Ensure we obtain the proper preimage in the response. if resp.PaymentError != "" { t.Fatalf("error when attempting recv: %v", resp.PaymentError) } else if !bytes.Equal(preimage, resp.PaymentPreimage) { t.Fatalf("preimage mismatch: expected %v, got %v", preimage, resp.GetPaymentPreimage()) } // Bob's invoice should now be found and marked as settled. payHash := &lnrpc.PaymentHash{ RHash: invoiceResp.RHash, } ctxt, _ = context.WithTimeout(ctxt, defaultTimeout) dbInvoice, err := net.Bob.LookupInvoice(ctxt, payHash) if err != nil { t.Fatalf("unable to lookup invoice: %v", err) } if !dbInvoice.Settled { t.Fatalf("bob's invoice should be marked as settled: %v", spew.Sdump(dbInvoice)) } // With the payment completed all balance related stats should be // properly updated. err = wait.NoError( assertAmountSent(paymentAmt, net.Alice, net.Bob), 3*time.Second, ) if err != nil { t.Fatalf(err.Error()) } // Create another invoice for Bob, this time leaving off the preimage // to one will be randomly generated. We'll test the proper // encoding/decoding of the zpay32 payment requests. invoice = &lnrpc.Invoice{ Memo: "test3", Value: paymentAmt, } ctxt, _ = context.WithTimeout(ctxt, defaultTimeout) invoiceResp, err = net.Bob.AddInvoice(ctxt, invoice) if err != nil { t.Fatalf("unable to add invoice: %v", err) } // Next send another payment, but this time using a zpay32 encoded // invoice rather than manually specifying the payment details. sendReq = &lnrpc.SendRequest{ PaymentRequest: invoiceResp.PaymentRequest, } ctxt, _ = context.WithTimeout(ctxb, defaultTimeout) resp, err = net.Alice.SendPaymentSync(ctxt, sendReq) if err != nil { t.Fatalf("unable to send payment: %v", err) } if resp.PaymentError != "" { t.Fatalf("error when attempting recv: %v", resp.PaymentError) } // The second payment should also have succeeded, with the balances // being update accordingly. err = wait.NoError( assertAmountSent(2*paymentAmt, net.Alice, net.Bob), 3*time.Second, ) if err != nil { t.Fatalf(err.Error()) } // Next send a key send payment. keySendPreimage := lntypes.Preimage{3, 4, 5, 11} keySendHash := keySendPreimage.Hash() sendReq = &lnrpc.SendRequest{ Dest: net.Bob.PubKey[:], Amt: paymentAmt, FinalCltvDelta: 40, PaymentHash: keySendHash[:], DestCustomRecords: map[uint64][]byte{ record.KeySendType: keySendPreimage[:], }, } ctxt, _ = context.WithTimeout(ctxb, defaultTimeout) resp, err = net.Alice.SendPaymentSync(ctxt, sendReq) if err != nil { t.Fatalf("unable to send payment: %v", err) } if resp.PaymentError != "" { t.Fatalf("error when attempting recv: %v", resp.PaymentError) } // The key send payment should also have succeeded, with the balances // being update accordingly. err = wait.NoError( assertAmountSent(3*paymentAmt, net.Alice, net.Bob), 3*time.Second, ) if err != nil { t.Fatalf(err.Error()) } ctxt, _ = context.WithTimeout(ctxb, channelCloseTimeout) closeChannelAndAssert(ctxt, t, net, net.Alice, chanPoint, false) }
main.go
package main import ( "log" "net/smtp" ) func
() { send("hello there") } func send(body string) { from := "[email protected]" pass := "..-" to := "..." msg := "From: " + from + "\n" + "To: " + to + "\n" + "Subject: Hello there\n\n" + body err := smtp.SendMail("smtp.gmail.com:587", smtp.PlainAuth("", from, pass, "smtp.gmail.com"), from, []string{to}, []byte(msg)) if err != nil { log.Printf("smtp error: %s", err) return } log.Print("sent, visit GMAIL") }
main
tests.rs
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ backup_types::transaction::{ backup::{TransactionBackupController, TransactionBackupOpt}, restore::{TransactionRestoreController, TransactionRestoreOpt}, }, storage::{local_fs::LocalFs, BackupStorage}, utils::{ backup_service_client::BackupServiceClient, test_utils::{tmp_db_empty, tmp_db_with_random_content}, GlobalBackupOpt, GlobalRestoreOpt, }, }; use backup_service::start_backup_service; use libra_config::utils::get_available_port; use libra_temppath::TempPath; use libra_types::transaction::Version; use libradb::GetRestoreHandler; use std::{mem::size_of, path::PathBuf, sync::Arc}; use storage_interface::DbReader; use tokio::time::Duration; #[test]
backup_dir.create_as_dir().unwrap(); let store: Arc<dyn BackupStorage> = Arc::new(LocalFs::new(backup_dir.path().to_path_buf())); let port = get_available_port(); let mut rt = start_backup_service(port, src_db); let client = Arc::new(BackupServiceClient::new(port)); let latest_version = blocks.last().unwrap().1.ledger_info().version(); let total_txns = blocks.iter().fold(0, |x, b| x + b.0.len()); assert_eq!(latest_version as usize + 1, total_txns); let txns = blocks .iter() .map(|(txns, _li)| txns) .flatten() .map(|txn_to_commit| txn_to_commit.transaction()) .collect::<Vec<_>>(); let max_chunk_size = txns .iter() .map(|t| lcs::to_bytes(t).unwrap().len()) .max() .unwrap() // biggest txn + 115 // size of a serialized TransactionInfo + size_of::<u32>(); // record len header let first_ver_to_backup = (total_txns / 4) as Version; let num_txns_to_backup = total_txns - first_ver_to_backup as usize; let target_version = first_ver_to_backup + total_txns as Version / 2; let num_txns_to_restore = (target_version - first_ver_to_backup + 1) as usize; let manifest_handle = rt .block_on( TransactionBackupController::new( TransactionBackupOpt { start_version: first_ver_to_backup, num_transactions: num_txns_to_backup, }, GlobalBackupOpt { max_chunk_size }, client, Arc::clone(&store), ) .run(), ) .unwrap(); rt.block_on( TransactionRestoreController::new( TransactionRestoreOpt { manifest_handle, replay_from_version: None, // max }, GlobalRestoreOpt { db_dir: PathBuf::new(), target_version: Some(target_version), }, store, Arc::new(tgt_db.get_restore_handler()), ) .run(), ) .unwrap(); let recovered_transactions = tgt_db .get_transactions( first_ver_to_backup, num_txns_to_restore as u64, target_version, false, ) .unwrap() .transactions; assert_eq!( recovered_transactions, txns.into_iter() .skip(first_ver_to_backup as usize) .take(num_txns_to_restore) .cloned() .collect::<Vec<_>>() ); rt.shutdown_timeout(Duration::from_secs(1)); }
fn end_to_end() { let (_src_db_dir, src_db, blocks) = tmp_db_with_random_content(); let (_tgt_db_dir, tgt_db) = tmp_db_empty(); let backup_dir = TempPath::new();
avax_elk.js
$(function() { consoleInit(main) }); const ELK_CONTRACT_ABI = [{"type":"constructor","stateMutability":"nonpayable","inputs":[{"type":"address","name":"_rewardsToken","internalType":"address"},{"type":"address","name":"_stakingToken","internalType":"address"}]},{"type":"event","name":"OwnershipTransferred","inputs":[{"type":"address","name":"previousOwner","internalType":"address","indexed":true},{"type":"address","name":"newOwner","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"Recovered","inputs":[{"type":"address","name":"token","internalType":"address","indexed":false},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"RewardAdded","inputs":[{"type":"uint256","name":"reward","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"RewardPaid","inputs":[{"type":"address","name":"user","internalType":"address","indexed":true},{"type":"uint256","name":"reward","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"RewardsDurationUpdated","inputs":[{"type":"uint256","name":"newDuration","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Staked","inputs":[{"type":"address","name":"user","internalType":"address","indexed":true},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Withdrawn","inputs":[{"type":"address","name":"user","internalType":"address","indexed":true},{"type":"uint256","name":"amount","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"balanceOf","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"earned","inputs":[{"type":"address","name":"account","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"exit","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"getReward","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"getRewardForDuration","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"lastTimeRewardApplicable","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"lastUpdateTime","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"notifyRewardAmount","inputs":[{"type":"uint256","name":"reward","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"owner","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"periodFinish","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"recoverERC20","inputs":[{"type":"address","name":"tokenAddress","internalType":"address"},{"type":"uint256","name":"tokenAmount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"renounceOwnership","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"rewardPerToken","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"rewardPerTokenStored","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"rewardRate","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"rewards","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"rewardsDuration","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IERC20"}],"name":"rewardsToken","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setRewardsDuration","inputs":[{"type":"uint256","name":"_rewardsDuration","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"stake","inputs":[{"type":"uint256","name":"amount","internalType":"uint256"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"stakeWithPermit","inputs":[{"type":"uint256","name":"amount","internalType":"uint256"},{"type":"uint256","name":"deadline","internalType":"uint256"},{"type":"uint8","name":"v","internalType":"uint8"},{"type":"bytes32","name":"r","internalType":"bytes32"},{"type":"bytes32","name":"s","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IERC20"}],"name":"stakingToken","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalSupply","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"transferOwnership","inputs":[{"type":"address","name":"newOwner","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"updatePeriodFinish","inputs":[{"type":"uint256","name":"timestamp","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"userRewardPerTokenPaid","inputs":[{"type":"address","name":"","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"withdraw","inputs":[{"type":"uint256","name":"amount","internalType":"uint256"}]}] const Pools = [ { //tokens: [xe[f.c.AVALANCHE], f.p[f.c.AVALANCHE]], stakingRewardAddress: "0x9080Bd46a55f8A32DB2B609C74f8125a08DafbC3" }, { //tokens: [xe[f.c.AVALANCHE], we[f.c.AVALANCHE]], stakingRewardAddress: "0x4235F9bE035541A69525Fa853e2369fe493BA936" }, { //tokens: [xe[f.c.AVALANCHE], je[f.c.AVALANCHE]], stakingRewardAddress: "0x777e391521a542430bDD59Be48b1eAc00117427c" }, { //tokens: [xe[f.c.AVALANCHE], Ce[f.c.AVALANCHE]], stakingRewardAddress: "0x2D9C1e87595c6ED24CfEC114549A955b7023E1a9" }, { //tokens: [xe[f.c.AVALANCHE], Ie[f.c.AVALANCHE]], stakingRewardAddress: "0xE18ae29256ee2d31f7A4AA72567fde1FF7d9895e" }, { //tokens: [xe[f.c.AVALANCHE], Te[f.c.AVALANCHE]], stakingRewardAddress: "0xfeeFf2fcb7fE9f3211abE643c3f49f3a4F04063A" }, { //tokens: [xe[f.c.AVALANCHE], Oe[f.c.AVALANCHE]], stakingRewardAddress: "0xC1E72BF3F97505537AdAd52639F3Bbf2DF5E5736" }, { //tokens: [xe[f.c.AVALANCHE], Qe[f.c.AVALANCHE]], stakingRewardAddress: "0x9bC04d39a721b48Ca33700214961aC5cC3622f76" }, { //tokens: [xe[f.c.AVALANCHE], Ve[f.c.AVALANCHE]], stakingRewardAddress: "0x99Ef222dBA70eb0A396115D3ad0633C88bc73582" }, { //tokens: [xe[f.c.AVALANCHE], We[f.c.AVALANCHE]], stakingRewardAddress: "0xA8d91C6093b700897e4654a71BE67fE017f10098" }, { //tokens: [xe[f.c.AVALANCHE], Ge[f.c.AVALANCHE]], stakingRewardAddress: "0x621B5aDC58ccE0F1EfA0c51007Ab9A923213f759" }, { //tokens: [xe[f.c.AVALANCHE], Ne[f.c.AVALANCHE]], stakingRewardAddress: "0xb961966caE73a66E96D22965dE8D253c0FcBcf04" }, { //tokens: [xe[f.c.AVALANCHE], Ye[f.c.AVALANCHE]], stakingRewardAddress: "0xec4676aAAE8B958464d087d4FaaA6731F0596ae9" }, { //tokens: [xe[f.c.AVALANCHE], He[f.c.AVALANCHE]], stakingRewardAddress: "0x325d72D3d0806fD2A45a6C44E3e51D18D8187117" }, { //tokens: [xe[f.c.AVALANCHE], qe[f.c.AVALANCHE]], stakingRewardAddress: "0x0DA14647cc52cD93cD5c57Bb67dC45de4CD12EF1" } ].map(p => { return { address: p.stakingRewardAddress, abi: ELK_CONTRACT_ABI, stakeTokenFunction: "stakingToken", rewardTokenFunction: "rewardsToken" }; } ) async function
() { const App = await init_ethers(); _print(`Initialized ${App.YOUR_ADDRESS}`); _print("Reading smart contracts...\n"); let tokens = {}; let prices = await getAvaxPrices(); await loadAvaxSynthetixPoolInfo(App, tokens, prices, Pools[0].abi, Pools[0].address, Pools[0].rewardTokenFunction, Pools[0].stakeTokenFunction); let p = await loadMultipleAvaxSynthetixPools(App, tokens, prices, Pools) _print_bold(`Total staked: $${formatMoney(p.staked_tvl)}`); if (p.totalUserStaked > 0) { _print(`You are staking a total of $${formatMoney(p.totalUserStaked)} at an APR of ${(p.totalAPR * 100).toFixed(2)}%\n`); } hideLoading(); }
main
Settings.js
import React, { Component } from "react"; import * as actions from "../../store/actions/index"; import { connect } from "react-redux"; import { Container, Col, Row, Form, Alert } from "react-bootstrap"; import Button from "../../components/UI/Button/Button"; import { Redirect } from "react-router-dom"; import Spinner from "../../components/UI/PacmanSpinner/PacmanSpinner"; import PageHeader from "../../components/PageHeader/PageHeader"; import classes from "./Settings.module.css"; class
extends Component { state = { monthlyIncome: "", monthlyExpense: "", currency: "", showAlert: false, }; componentDidMount() { // Setting the saved settings to state this.setState({ monthlyIncome: this.props.monthlyIncome, monthlyExpense: this.props.monthlyExpense, currency: this.props.currency, }); } saveChanges = () => { //TODO: Validation this.props.saveChanges( this.state.monthlyIncome, this.state.monthlyExpense, this.state.currency ); this.setState({ showAlert: true }); }; onChangeHandler = (e) => { const { name, value } = e.target; this.setState({ [name]: value }); }; render() { let alert = null; if (this.state.showAlert) { alert = ( <Alert variant={"success"} style={{ fontSize: "1.8rem" }}> Changes were made successfuly! </Alert> ); } return ( <> <PageHeader title="Settings" desc="Change the app to your preferences" /> {this.props.loading ? ( <Spinner /> ) : ( <Container className={classes.SettingsWrapper}> <Row className={classes.Desc}> <Col md lg xl={12}> <div className={classes.User}> <span className={classes.UserAvatar}> {this.props.name ? this.props.name[0] : null} </span> <h3>{this.props.name}</h3> <p style={{ color: "gray" }}> {this.props.email} </p> <div className={classes.Buttons}> {this.props.isAuth ? ( <Button clickEvent={this.props.onLogout} > Logout </Button> ) : ( <Redirect to="/portal" /> )} <Button variant="outline-green"> Download data </Button> </div> </div> </Col> </Row> <Row className={classes.UserSettings}> <p> By letting Leafeon know your personal preferences, we can make your user more fun and interesting. </p> <Col md lg xl={12}> <Form.Group controlId="currency"> <Form.Label>Currency</Form.Label> <Form.Control type="text" name="currency" placeholder="€, $ ..." value={this.state.currency} onChange={this.onChangeHandler} /> </Form.Group> <h3> Goals{" "} <span style={{ fontSize: "15px", color: "gray", }} > (Currently not working) </span> </h3> <Form.Group controlId="monthlyincome"> <Form.Label> Monthly Income / Salary </Form.Label> <Form.Control name="monthlyIncome" type="number" placeholder="Optional constant incomes " value={this.state.monthlyIncome} onChange={this.onChangeHandler} /> </Form.Group> <Form.Group controlId="monthlyexpense"> <Form.Label>Monthly Expense</Form.Label> <Form.Control name="monthlyExpense" type="number" placeholder="Optional constant sum of expenses " value={this.state.monthlyExpense} onChange={this.onChangeHandler} /> </Form.Group> <Button clickEvent={this.saveChanges}> Save changes </Button> </Col> </Row> {alert} </Container> )} </> ); } } const mapStateToProps = (state) => { return { isAuth: state.auth.token !== null, name: state.auth.name, email: state.auth.email, currency: state.settings.currency, monthlyIncome: state.settings.monthlyIncome, monthlyExpense: state.settings.monthlyExpense, loading: state.settings.loading, }; }; const mapDispatchToProps = (dispatch) => { return { onLogout: () => dispatch(actions.logout()), saveChanges: (monthlyIncome, monthlyExpense, currency) => dispatch( actions.saveChanges(monthlyIncome, monthlyExpense, currency) ), onFetchSettingsFromLocalStorage: () => dispatch(actions.fetchSettings()), }; }; export default connect( mapStateToProps, mapDispatchToProps )(Settings);
Settings
unused-extern-crate.rs
// check-pass // aux-crate:panic_item=panic-item.rs // @has unused_extern_crate/index.html
channel.py
from replit import db
# Posts message to discord channel (translated according to channel) # ======================================================== async def say(channel, message, arguments=None): message = locales.get(get_channel_lang(channel.id), message) if arguments is not None: await channel.send(message.format(*arguments)) else: await channel.send(message) # ======================================================== # Sets the language to montitor for the given channel # ======================================================== def set_channel_lang(channel, code): db[channel] = code # ======================================================== # Gets the language to montitor for the given channel # ======================================================== def get_channel_lang(channel): try: return db[channel] except: return 'en' # ======================================================== # Removes channel lanaguage association # ======================================================== def remove_channel_lang(channel): if channel_has_lang(channel): del db[channel] # ======================================================== # Determine if channel has language # ======================================================== def channel_has_lang(channel): return channel in db.keys()
from locales import locales # ========================================================
test_email_alert.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe, frappe.utils, frappe.utils.scheduler import unittest test_records = frappe.get_test_records('Email Alert') class TestEmailAlert(unittest.TestCase): def
(self): frappe.db.sql("""delete from `tabBulk Email`""") frappe.set_user("[email protected]") def tearDown(self): frappe.set_user("Administrator") def test_new_and_save(self): communication = frappe.new_doc("Communication") communication.communication_type = 'Comment' communication.subject = "test" communication.content = "test" communication.insert(ignore_permissions=True) self.assertTrue(frappe.db.get_value("Bulk Email", {"reference_doctype": "Communication", "reference_name": communication.name, "status":"Not Sent"})) frappe.db.sql("""delete from `tabBulk Email`""") communication.content = "test 2" communication.save() self.assertTrue(frappe.db.get_value("Bulk Email", {"reference_doctype": "Communication", "reference_name": communication.name, "status":"Not Sent"})) def test_condition(self): event = frappe.new_doc("Event") event.subject = "test", event.event_type = "Private" event.starts_on = "2014-06-06 12:00:00" event.insert() self.assertFalse(frappe.db.get_value("Bulk Email", {"reference_doctype": "Event", "reference_name": event.name, "status":"Not Sent"})) event.event_type = "Public" event.save() self.assertTrue(frappe.db.get_value("Bulk Email", {"reference_doctype": "Event", "reference_name": event.name, "status":"Not Sent"})) def test_value_changed(self): event = frappe.new_doc("Event") event.subject = "test", event.event_type = "Private" event.starts_on = "2014-06-06 12:00:00" event.insert() self.assertFalse(frappe.db.get_value("Bulk Email", {"reference_doctype": "Event", "reference_name": event.name, "status":"Not Sent"})) event.subject = "test 1" event.save() self.assertFalse(frappe.db.get_value("Bulk Email", {"reference_doctype": "Event", "reference_name": event.name, "status":"Not Sent"})) event.description = "test" event.save() self.assertTrue(frappe.db.get_value("Bulk Email", {"reference_doctype": "Event", "reference_name": event.name, "status":"Not Sent"})) def test_date_changed(self): event = frappe.new_doc("Event") event.subject = "test", event.event_type = "Private" event.starts_on = "2014-01-01 12:00:00" event.insert() self.assertFalse(frappe.db.get_value("Bulk Email", {"reference_doctype": "Event", "reference_name": event.name, "status":"Not Sent"})) frappe.utils.scheduler.trigger(frappe.local.site, "daily", now=True) # not today, so no alert self.assertFalse(frappe.db.get_value("Bulk Email", {"reference_doctype": "Event", "reference_name": event.name, "status":"Not Sent"})) event.starts_on = frappe.utils.add_days(frappe.utils.nowdate(), 2) + " 12:00:00" event.save() self.assertFalse(frappe.db.get_value("Bulk Email", {"reference_doctype": "Event", "reference_name": event.name, "status":"Not Sent"})) frappe.utils.scheduler.trigger(frappe.local.site, "daily", now=True) # today so show alert self.assertTrue(frappe.db.get_value("Bulk Email", {"reference_doctype": "Event", "reference_name": event.name, "status":"Not Sent"}))
setUp
hint.py
assert ENCRYPTION_KEY.islower()
protocol.py
# # pieces - An experimental BitTorrent client # # Copyright 2016 [email protected] # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import asyncio import logging import struct from asyncio import Queue from concurrent.futures import CancelledError import datetime import bitstring # The default request size for blocks of pieces is 2^14 bytes. # # NOTE: The official specification states that 2^15 is the default request # size - but in reality all implementations use 2^14. See the # unofficial specification for more details on this matter. # # https://wiki.theory.org/BitTorrentSpecification # REQUEST_SIZE = 2**14 HANDSHAKE_TIMEOUT = 4 class ProtocolError(BaseException): pass class PeerConnection: """ A peer connection used to download and upload pieces. The peer connection will consume one available peer from the given queue. Based on the peer details the PeerConnection will try to open a connection and perform a BitTorrent handshake. After a successful handshake, the PeerConnection will be in a *choked* state, not allowed to request any data from the remote peer. After sending an interested message the PeerConnection will be waiting to get *unchoked*. Once the remote peer unchoked us, we can start requesting pieces. The PeerConnection will continue to request pieces for as long as there are pieces left to request, or until the remote peer disconnects. If the connection with a remote peer drops, the PeerConnection will consume the next available peer from off the queue and try to connect to that one instead. """ def __init__(self, queue: Queue, info_hash, peer_id, piece_manager, on_block_cb=None): """ Constructs a PeerConnection and add it to the asyncio event-loop. Use `stop` to abort this connection and any subsequent connection attempts :param queue: The async Queue containing available peers :param info_hash: The SHA1 hash for the meta-data's info :param peer_id: Our peer ID used to to identify ourselves :param piece_manager: The manager responsible to determine which pieces to request :param on_block_cb: The callback function to call when a block is received from the remote peer """ self.my_state = [] self.peer_state = [] self.queue = queue self.info_hash = info_hash self.peer_id = peer_id self.remote_id = None self.writer = None self.reader = None self.piece_manager = piece_manager self.on_block_cb = on_block_cb self.future = asyncio.ensure_future(self._start()) # Start this worker async def _start(self): while 'stopped' not in self.my_state: ip, port = await self.queue.get() logging.info('Got assigned peer with: {ip}'.format(ip=ip)) try: # TODO For some reason it does not seem to work to open a new # connection if the first one drops (i.e. second loop). self.reader, self.writer = await asyncio.open_connection( ip, port) logging.info('Connection open to peer: {ip}'.format(ip=ip)) # It's our responsibility to initiate the handshake. buffer = await self._handshake() # TODO Add support for sending data # Sending BitField is optional and not needed when client does # not have any pieces. Thus we do not send any bitfield message # The default state for a connection is that peer is not # interested and we are choked self.my_state.append('choked') # Let the peer know we're interested in downloading pieces await self._send_interested() self.my_state.append('interested') # Start reading responses as a stream of messages for as # long as the connection is open and data is transmitted async for message in PeerStreamIterator(self.reader, buffer): if 'stopped' in self.my_state: break if type(message) is BitField: self.piece_manager.add_peer(self.remote_id, message.bitfield) elif type(message) is Interested: self.peer_state.append('interested') elif type(message) is NotInterested: if 'interested' in self.peer_state: self.peer_state.remove('interested') elif type(message) is Choke: self.my_state.append('choked') """ written/modified by Stefan Brynielsson, May 2019 """ if "pending_request" in self.my_state: self.my_state.remove('pending_request') elif type(message) is Unchoke: if 'choked' in self.my_state: self.my_state.remove('choked') """ written/modified by Stefan Brynielsson, May 2019 """ if "pending_request" in self.my_state: self.my_state.remove('pending_request') elif type(message) is Have: self.piece_manager.update_peer(self.remote_id, message.index) elif type(message) is KeepAlive: """ Written/modified by Stefan Brynielsson, May 2019 """ break elif type(message) is Piece: self.my_state.remove('pending_request') self.on_block_cb( peer_id=self.remote_id, piece_index=message.index, block_offset=message.begin, data=message.block) elif type(message) is Request: # TODO Add support for sending data logging.info('Ignoring the received Request message.') elif type(message) is Cancel: # TODO Add support for sending data logging.info('Ignoring the received Cancel message.') # Send block request to remote peer if we're interested if 'choked' not in self.my_state: if 'interested' in self.my_state: if 'pending_request' not in self.my_state: self.my_state.append('pending_request') await self._request_piece() except ProtocolError as e: logging.exception('Protocol error') except (ConnectionRefusedError, TimeoutError): logging.warning('Unable to connect to peer') except (ConnectionResetError, CancelledError): logging.warning('Connection closed') except Exception as e: logging.exception('An error occurred') self.cancel() raise e self.cancel() def cancel(self): """ Sends the cancel message to the remote peer and closes the connection. """ logging.info('Closing peer {id}'.format(id=self.remote_id)) if not self.future.done(): self.future.cancel() if self.writer: self.writer.close() self.queue.task_done() def stop(self): """ Stop this connection from the current peer (if a connection exist) and from connecting to any new peer. """ # Set state to stopped and cancel our future to break out of the loop. # The rest of the cleanup will eventually be managed by loop calling # `cancel`. self.my_state.append('stopped') if not self.future.done(): self.future.cancel() async def _request_piece(self): block = self.piece_manager.next_request(self.remote_id) if block: message = Request(block.piece, block.offset, block.length).encode() logging.debug('Requesting block {block} for piece {piece} ' 'of {length} bytes from peer {peer}'.format( piece=block.piece, block=block.offset, length=block.length, peer=self.remote_id)) self.writer.write(message) await self.writer.drain() async def _handshake(self): """ Send the initial handshake to the remote peer and wait for the peer to respond with its handshake. """ self.writer.write(Handshake(self.info_hash, self.peer_id).encode()) """ Written/modified by Stefan Brynielsson, May 2019 """ time = datetime.datetime.now() await self.writer.drain() buf = b'' while len(buf) < Handshake.length: buf = await self.reader.read(PeerStreamIterator.CHUNK_SIZE) """ Written/modified by Stefan Brynielsson, May 2019 """ # End the handshake if it takes longer than HANDSHAKE_TIMEOUT seconds if (datetime.datetime.now() - time).total_seconds() > HANDSHAKE_TIMEOUT and len(buf) < Handshake.length: raise TimeoutError('NO handshake response') response = Handshake.decode(buf[:Handshake.length]) if not response: raise ProtocolError('Unable receive and parse a handshake') if not response.info_hash == self.info_hash: raise ProtocolError('Handshake with invalid info_hash') # TODO: According to spec we should validate that the peer_id received # from the peer match the peer_id received from the tracker. self.remote_id = response.peer_id logging.info('Handshake with peer was successful') # We need to return the remaining buffer data, since we might have # read more bytes then the size of the handshake message and we need # those bytes to parse the next message. return buf[Handshake.length:] async def _send_interested(self): message = Interested() logging.debug('Sending message: {type}'.format(type=message)) self.writer.write(message.encode()) await self.writer.drain() class PeerStreamIterator: """ The `PeerStreamIterator` is an async iterator that continuously reads from the given stream reader and tries to parse valid BitTorrent messages from off that stream of bytes. If the connection is dropped, something fails the iterator will abort by raising the `StopAsyncIteration` error ending the calling iteration. """ CHUNK_SIZE = 10*1024 def __init__(self, reader, initial: bytes = None): self.reader = reader self.buffer = initial if initial else b'' async def __aiter__(self): return self async def __anext__(self): # Read data from the socket. When we have enough data to parse, parse # it and return the message. Until then keep reading from stream while True: try: data = await self.reader.read(PeerStreamIterator.CHUNK_SIZE) if data:
else: logging.debug('No data read from stream') if self.buffer: message = self.parse() if message: return message raise StopAsyncIteration() except ConnectionResetError: logging.debug('Connection closed by peer') raise StopAsyncIteration() except CancelledError: raise StopAsyncIteration() except StopAsyncIteration as e: # Cath to stop logging raise e except Exception: logging.exception('Error when iterating over stream!') raise StopAsyncIteration() raise StopAsyncIteration() def parse(self): """ Tries to parse protocol messages if there is enough bytes read in the buffer. :return The parsed message, or None if no message could be parsed """ # Each message is structured as: # <length prefix><message ID><payload> # # The `length prefix` is a four byte big-endian value # The `message ID` is a decimal byte # The `payload` is the value of `length prefix` # # The message length is not part of the actual length. So another # 4 bytes needs to be included when slicing the buffer. header_length = 4 if len(self.buffer) > 4: # 4 bytes is needed to identify the message message_length = struct.unpack('>I', self.buffer[0:4])[0] if message_length == 0: return KeepAlive() if len(self.buffer) >= message_length: message_id = struct.unpack('>b', self.buffer[4:5])[0] def _consume(): """Consume the current message from the read buffer""" self.buffer = self.buffer[header_length + message_length:] def _data(): """"Extract the current message from the read buffer""" return self.buffer[:header_length + message_length] if message_id is PeerMessage.BitField: data = _data() _consume() return BitField.decode(data) elif message_id is PeerMessage.Interested: _consume() return Interested() elif message_id is PeerMessage.NotInterested: _consume() return NotInterested() elif message_id is PeerMessage.Choke: _consume() return Choke() elif message_id is PeerMessage.Unchoke: _consume() return Unchoke() elif message_id is PeerMessage.Have: data = _data() _consume() return Have.decode(data) elif message_id is PeerMessage.Piece: data = _data() _consume() return Piece.decode(data) elif message_id is PeerMessage.Request: data = _data() _consume() return Request.decode(data) elif message_id is PeerMessage.Cancel: data = _data() _consume() return Cancel.decode(data) else: logging.info('Unsupported message!') else: logging.debug('Not enough in buffer in order to parse') return None class PeerMessage: """ A message between two peers. All of the remaining messages in the protocol take the form of: <length prefix><message ID><payload> - The length prefix is a four byte big-endian value. - The message ID is a single decimal byte. - The payload is message dependent. NOTE: The Handshake messageis different in layout compared to the other messages. Read more: https://wiki.theory.org/BitTorrentSpecification#Messages BitTorrent uses Big-Endian (Network Byte Order) for all messages, this is declared as the first character being '>' in all pack / unpack calls to the Python's `struct` module. """ Choke = 0 Unchoke = 1 Interested = 2 NotInterested = 3 Have = 4 BitField = 5 Request = 6 Piece = 7 Cancel = 8 Port = 9 Handshake = None # Handshake is not really part of the messages KeepAlive = None # Keep-alive has no ID according to spec def encode(self) -> bytes: """ Encodes this object instance to the raw bytes representing the entire message (ready to be transmitted). """ pass @classmethod def decode(cls, data: bytes): """ Decodes the given BitTorrent message into a instance for the implementing type. """ pass class Handshake(PeerMessage): """ The handshake message is the first message sent and then received from a remote peer. The messages is always 68 bytes long (for this version of BitTorrent protocol). Message format: <pstrlen><pstr><reserved><info_hash><peer_id> In version 1.0 of the BitTorrent protocol: pstrlen = 19 pstr = "BitTorrent protocol". Thus length is: 49 + len(pstr) = 68 bytes long. """ length = 49 + 19 def __init__(self, info_hash: bytes, peer_id: bytes): """ Construct the handshake message :param info_hash: The SHA1 hash for the info dict :param peer_id: The unique peer id """ if isinstance(info_hash, str): info_hash = info_hash.encode('utf-8') if isinstance(peer_id, str): peer_id = peer_id.encode('utf-8') self.info_hash = info_hash self.peer_id = peer_id def encode(self) -> bytes: """ Encodes this object instance to the raw bytes representing the entire message (ready to be transmitted). """ return struct.pack( '>B19s8x20s20s', 19, # Single byte (B) b'BitTorrent protocol', # String 19s # Reserved 8x (pad byte, no value) self.info_hash, # String 20s self.peer_id) # String 20s @classmethod def decode(cls, data: bytes): """ Decodes the given BitTorrent message into a handshake message, if not a valid message, None is returned. """ logging.debug('Decoding Handshake of length: {length}'.format( length=len(data))) if len(data) < (49 + 19): return None parts = struct.unpack('>B19s8x20s20s', data) return cls(info_hash=parts[2], peer_id=parts[3]) def __str__(self): return 'Handshake' class KeepAlive(PeerMessage): """ The Keep-Alive message has no payload and length is set to zero. Message format: <len=0000> """ def __str__(self): return 'KeepAlive' class BitField(PeerMessage): """ The BitField is a message with variable length where the payload is a bit array representing all the bits a peer have (1) or does not have (0). Message format: <len=0001+X><id=5><bitfield> """ def __init__(self, data): self.bitfield = bitstring.BitArray(bytes=data) def encode(self) -> bytes: """ Encodes this object instance to the raw bytes representing the entire message (ready to be transmitted). """ bits_length = len(self.bitfield) return struct.pack('>Ib' + str(bits_length) + 's', 1 + bits_length, PeerMessage.BitField, bytes(self.bitfield)) @classmethod def decode(cls, data: bytes): message_length = struct.unpack('>I', data[:4])[0] logging.debug('Decoding BitField of length: {length}'.format( length=message_length)) parts = struct.unpack('>Ib' + str(message_length - 1) + 's', data) return cls(parts[2]) def __str__(self): return 'BitField' class Interested(PeerMessage): """ The interested message is fix length and has no payload other than the message identifiers. It is used to notify each other about interest in downloading pieces. Message format: <len=0001><id=2> """ def encode(self) -> bytes: """ Encodes this object instance to the raw bytes representing the entire message (ready to be transmitted). """ return struct.pack('>Ib', 1, # Message length PeerMessage.Interested) def __str__(self): return 'Interested' class NotInterested(PeerMessage): """ The not interested message is fix length and has no payload other than the message identifier. It is used to notify each other that there is no interest to download pieces. Message format: <len=0001><id=3> """ def __str__(self): return 'NotInterested' class Choke(PeerMessage): """ The choke message is used to tell the other peer to stop send request messages until unchoked. Message format: <len=0001><id=0> """ def __str__(self): return 'Choke' class Unchoke(PeerMessage): """ Unchoking a peer enables that peer to start requesting pieces from the remote peer. Message format: <len=0001><id=1> """ def __str__(self): return 'Unchoke' class Have(PeerMessage): """ Represents a piece successfully downloaded by the remote peer. The piece is a zero based index of the torrents pieces """ def __init__(self, index: int): self.index = index def encode(self): return struct.pack('>IbI', 5, # Message length PeerMessage.Have, self.index) @classmethod def decode(cls, data: bytes): logging.debug('Decoding Have of length: {length}'.format( length=len(data))) index = struct.unpack('>IbI', data)[2] return cls(index) def __str__(self): return 'Have' class Request(PeerMessage): """ The message used to request a block of a piece (i.e. a partial piece). The request size for each block is 2^14 bytes, except the final block that might be smaller (since not all pieces might be evenly divided by the request size). Message format: <len=0013><id=6><index><begin><length> """ def __init__(self, index: int, begin: int, length: int = REQUEST_SIZE): """ Constructs the Request message. :param index: The zero based piece index :param begin: The zero based offset within a piece :param length: The requested length of data (default 2^14) """ self.index = index self.begin = begin self.length = length def encode(self): return struct.pack('>IbIII', 13, PeerMessage.Request, self.index, self.begin, self.length) @classmethod def decode(cls, data: bytes): logging.debug('Decoding Request of length: {length}'.format( length=len(data))) # Tuple with (message length, id, index, begin, length) parts = struct.unpack('>IbIII', data) return cls(parts[2], parts[3], parts[4]) def __str__(self): return 'Request' class Piece(PeerMessage): """ A block is a part of a piece mentioned in the meta-info. The official specification refer to them as pieces as well - which is quite confusing the unofficial specification refers to them as blocks however. So this class is named `Piece` to match the message in the specification but really, it represents a `Block` (which is non-existent in the spec). Message format: <length prefix><message ID><index><begin><block> """ # The Piece message length without the block data length = 9 def __init__(self, index: int, begin: int, block: bytes): """ Constructs the Piece message. :param index: The zero based piece index :param begin: The zero based offset within a piece :param block: The block data """ self.index = index self.begin = begin self.block = block def encode(self): message_length = Piece.length + len(self.block) return struct.pack('>IbII' + str(len(self.block)) + 's', message_length, PeerMessage.Piece, self.index, self.begin, self.block) @classmethod def decode(cls, data: bytes): logging.debug('Decoding Piece of length: {length}'.format( length=len(data))) length = struct.unpack('>I', data[:4])[0] parts = struct.unpack('>IbII' + str(length - Piece.length) + 's', data[:length+4]) return cls(parts[2], parts[3], parts[4]) def __str__(self): return 'Piece' class Cancel(PeerMessage): """ The cancel message is used to cancel a previously requested block (in fact the message is identical (besides from the id) to the Request message). Message format: <len=0013><id=8><index><begin><length> """ def __init__(self, index, begin, length: int = REQUEST_SIZE): self.index = index self.begin = begin self.length = length def encode(self): return struct.pack('>IbIII', 13, PeerMessage.Cancel, self.index, self.begin, self.length) @classmethod def decode(cls, data: bytes): logging.debug('Decoding Cancel of length: {length}'.format( length=len(data))) # Tuple with (message length, id, index, begin, length) parts = struct.unpack('>IbIII', data) return cls(parts[2], parts[3], parts[4]) def __str__(self): return 'Cancel'
self.buffer += data message = self.parse() if message: return message
urls.py
from django.conf.urls import url from test_app.views.home import Home from test_app.views.ajax import Ajax app_name = "test_app" urlpatterns = [ url(regex=r"^$", view=Home, name="home"), url(regex=r"^ajax$", view=Ajax, name="ajax"),
]
sqrl_url.rs
use url::{Url, ParseError}; use std::collections::HashMap; #[derive(Debug)] pub struct SqrlUrl { pub original: String, pub url: Url, pub parsed_query: HashMap<String, String>, } impl SqrlUrl { pub fn parse(url: &str) -> SqrlUrl { let url = Url::parse(url).unwrap(); let parsed_query = url::form_urlencoded::parse(url.query().unwrap().as_bytes()).into_owned().collect(); SqrlUrl { original: url.to_string(), url: url, parsed_query: parsed_query, } } pub fn auth_domain(&self) -> String { let domain = self.url.host_str().unwrap().to_lowercase(); match self.x() { Some(x) => format!("{}{}", domain, self.url.path().chars().take(x).collect::<String>()),
_ => domain } } /// x query parameter, specifies the maximum extra path for auth_domain fn x(&self) -> Option<usize> { self.parsed_query.get("x").and_then(|i| usize::from_str_radix(i, 10).ok()) } /// nut query parameter pub fn nut(&self) -> Option<&String> { //self.parsed_query.get("nut").map(|nut| nut.clone()) self.parsed_query.get("nut") } /// cancel query parameter pub fn can(&self) -> Option<String> { self.parsed_query.get("can").map(|input| String::from_utf8(base64::decode_config(&input, base64::URL_SAFE).unwrap()).unwrap() ) } } #[cfg(test)] mod tests { #[test] fn it_parses_auth_domain_examples() { // domain lowercased assert_eq!(super::SqrlUrl::parse("sqrl://ExAmPlE.cOm/?nut=...").auth_domain(), "example.com"); // ignore port override assert_eq!(super::SqrlUrl::parse("sqrl://example.com:44344/?nut=...").auth_domain(), "example.com"); // ignore username@m assert_eq!(super::SqrlUrl::parse("sqrl://[email protected]/?nut=...").auth_domain(), "example.com"); // ignore user:pass@ assert_eq!(super::SqrlUrl::parse("qrl://Jonny:[email protected]/?nut=...").auth_domain(), "example.com"); // extend auth domain assert_eq!(super::SqrlUrl::parse("sqrl://example.com/jimbo/?x=6&nut=...").auth_domain(), "example.com/jimbo"); // extension’s CASE and end extension at ‘?’ assert_eq!(super::SqrlUrl::parse("sqrl://EXAMPLE.COM/JIMBO?x=16&nut=...").auth_domain(), "example.com/JIMBO"); // TODO: what about ipv4 and ipv6 } #[test] fn it_parses_the_nut() { // TODO: check the nut assert_eq!(super::SqrlUrl::parse("sqrl://EXAMPLE.COM/JIMBO?x=16&nut=...").nut(), Some(&"...".to_string())); assert_eq!(super::SqrlUrl::parse("sqrl://EXAMPLE.COM/JIMBO?x=16&nut=ailsdjfasjdflij42l2j4rl234jrl23rj").nut(), Some(&"ailsdjfasjdflij42l2j4rl234jrl23rj".to_string())); } #[test] fn it_parses_the_can() { // TODO: check the can parameter some more assert_eq!(super::SqrlUrl::parse("sqrl://EXAMPLE.COM/JIMBO?x=16&nut=...").can(), None); assert_eq!(super::SqrlUrl::parse("sqrl://EXAMPLE.COM/JIMBO?x=16&nut=...&can=aHR0cHM6Ly9zcXJsLmdyYy5jb20vZGVtbw").can(), Some("https://sqrl.grc.com/demo".to_string())); } }
defaults.py
import repo from collectors import basic def extract_content(url, soup): return soup.title.string # extract page's title def store_content(url, content): # store in a hash with the URL as the key and the title as the content repo.set_content(url, content)
def allow_url_filter(url): return True # allow all by default def get_html(url): return basic.get_html(url)
conditions.rs
fn
() { if 1 < 2 {} if let Some(x) = o {} if let | Err(e) = r {} if let V1(s) | V2(s) = value {} if let | Cat(name) | Dog(name) | Parrot(name) = animal {} if let Ok(V1(s) | V2(s)) = value {} while 1 < 2 {} while let Some(x) = o {} while let | Err(e) = r {} while let V1(s) | V2(s) = value {} while let | Cat(name) | Dog(name) | Parrot(name) = animal {} while let Ok(V1(s) | V2(s)) = value {} }
main
ButtonExpToExcel.rs_ru.js
ButtonExpToExcel.prototype.DEF_TITLE = "экспорт в Excel";
ButtonExpToExcel.prototype.DEF_CAPTION="Excel";
object.rs
use super::{Value, Function}; pub enum Object { String(String),
Array(Vec<Value>), Function(Function) }
hook.go
/* Copyright 2020 The Operator-SDK Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package hook import ( "sync" "github.com/go-logr/logr" sdkhandler "github.com/operator-framework/operator-lib/handler" "helm.sh/helm/v3/pkg/release" "helm.sh/helm/v3/pkg/releaseutil" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/source" "sigs.k8s.io/yaml" "github.com/operator-framework/helm-operator-plugins/pkg/hook" "github.com/operator-framework/helm-operator-plugins/pkg/internal/sdk/controllerutil" "github.com/operator-framework/helm-operator-plugins/pkg/internal/sdk/predicate" "github.com/operator-framework/helm-operator-plugins/pkg/manifestutil" ) func
(c controller.Controller, rm meta.RESTMapper) hook.PostHook { return &dependentResourceWatcher{ controller: c, restMapper: rm, m: sync.Mutex{}, watches: make(map[schema.GroupVersionKind]struct{}), } } type dependentResourceWatcher struct { controller controller.Controller restMapper meta.RESTMapper m sync.Mutex watches map[schema.GroupVersionKind]struct{} } func (d *dependentResourceWatcher) Exec(owner *unstructured.Unstructured, rel release.Release, log logr.Logger) error { // using predefined functions for filtering events dependentPredicate := predicate.DependentPredicateFuncs() resources := releaseutil.SplitManifests(rel.Manifest) d.m.Lock() defer d.m.Unlock() for _, r := range resources { var obj unstructured.Unstructured err := yaml.Unmarshal([]byte(r), &obj) if err != nil { return err } depGVK := obj.GroupVersionKind() if _, ok := d.watches[depGVK]; ok || depGVK.Empty() { continue } useOwnerRef, err := controllerutil.SupportsOwnerReference(d.restMapper, owner, &obj) if err != nil { return err } if useOwnerRef && !manifestutil.HasResourcePolicyKeep(obj.GetAnnotations()) { if err := d.controller.Watch(&source.Kind{Type: &obj}, &handler.EnqueueRequestForOwner{ OwnerType: owner, IsController: true, }, dependentPredicate); err != nil { return err } } else { if err := d.controller.Watch(&source.Kind{Type: &obj}, &sdkhandler.EnqueueRequestForAnnotation{ Type: owner.GetObjectKind().GroupVersionKind().GroupKind(), }, dependentPredicate); err != nil { return err } } d.watches[depGVK] = struct{}{} log.V(1).Info("Watching dependent resource", "dependentAPIVersion", depGVK.GroupVersion(), "dependentKind", depGVK.Kind) } return nil }
NewDependentResourceWatcher
abort_on_drop.rs
// Copyright 2021, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use std::{ future::Future, ops::Deref, pin::Pin, task::{Context, Poll}, }; use tokio::task; /// A task JoinHandle that aborts the inner task associated with this handle if it is dropped. /// Awaiting a cancelled task might complete as usual if the task was already completed before the time /// it was cancelled, otherwise it will complete with a Err(JoinError::Cancelled). pub struct AbortOnDropJoinHandle<T> { inner: task::JoinHandle<T>, } impl<T> From<task::JoinHandle<T>> for AbortOnDropJoinHandle<T> { fn from(handle: task::JoinHandle<T>) -> Self { Self { inner: handle } } } impl<T> Deref for AbortOnDropJoinHandle<T> { type Target = task::JoinHandle<T>; fn deref(&self) -> &Self::Target
} impl<T> Drop for AbortOnDropJoinHandle<T> { fn drop(&mut self) { self.inner.abort(); } } impl<T> Future for AbortOnDropJoinHandle<T> { type Output = Result<T, task::JoinError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Pin::new(&mut self.inner).poll(cx) } }
{ &self.inner }
api_op_DescribeResourcePolicies.go
// Code generated by smithy-go-codegen DO NOT EDIT. package cloudwatchlogs import ( "context" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" "github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types" "github.com/aws/smithy-go/middleware" smithyhttp "github.com/aws/smithy-go/transport/http" ) // Lists the resource policies in this account. func (c *Client) DescribeResourcePolicies(ctx context.Context, params *DescribeResourcePoliciesInput, optFns ...func(*Options)) (*DescribeResourcePoliciesOutput, error) { if params == nil { params = &DescribeResourcePoliciesInput{} } result, metadata, err := c.invokeOperation(ctx, "DescribeResourcePolicies", params, optFns, addOperationDescribeResourcePoliciesMiddlewares) if err != nil { return nil, err } out := result.(*DescribeResourcePoliciesOutput) out.ResultMetadata = metadata return out, nil } type DescribeResourcePoliciesInput struct { // The maximum number of resource policies to be displayed with one call of this // API. Limit *int32 // The token for the next set of items to return. The token expires after 24 hours. NextToken *string } type DescribeResourcePoliciesOutput struct { // The token for the next set of items to return. The token expires after 24 hours. NextToken *string // The resource policies that exist in this account. ResourcePolicies []types.ResourcePolicy // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata } func addOperationDescribeResourcePoliciesMiddlewares(stack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeResourcePolicies{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeResourcePolicies{}, middleware.After) if err != nil { return err } if err = addSetLoggerMiddleware(stack, options); err != nil { return err } if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil { return err } if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { return err } if err = addResolveEndpointMiddleware(stack, options); err != nil { return err } if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { return err } if err = addRetryMiddlewares(stack, options); err != nil { return err } if err = addHTTPSignerV4Middleware(stack, options); err != nil { return err } if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil
if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeResourcePolicies(options.Region), middleware.Before); err != nil { return err } if err = addRequestIDRetrieverMiddleware(stack); err != nil { return err } if err = addResponseErrorMiddleware(stack); err != nil { return err } if err = addRequestResponseLogging(stack, options); err != nil { return err } return nil } func newServiceMetadataMiddleware_opDescribeResourcePolicies(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "logs", OperationName: "DescribeResourcePolicies", } }
{ return err }
dotformat_test.go
package testjson import ( "bufio" "bytes" "io" "math/rand" "runtime" "strings" "testing" "testing/quick" "time" "unicode/utf8" "gotest.tools/assert" "gotest.tools/assert/cmp" "gotest.tools/golden" "gotest.tools/gotestsum/internal/dotwriter" "gotest.tools/skip" ) func TestScanTestOutput_WithDotsFormatter(t *testing.T) { defer patchPkgPathPrefix("github.com/gotestyourself/gotestyourself")() out := new(bytes.Buffer) dotfmt := &dotFormatter{ pkgs: make(map[string]*dotLine), writer: dotwriter.New(out), termWidth: 80, } shim := newFakeHandler(dotfmt, "go-test-json") exec, err := ScanTestOutput(shim.Config(t)) assert.NilError(t, err) actual := removeSummaryTime(t, out) golden.Assert(t, actual, outFile("dots-format")) golden.Assert(t, shim.err.String(), "dots-format.err") assert.DeepEqual(t, exec, expectedExecution, cmpExecutionShallow) } func outFile(name string) string { if runtime.GOOS == "windows" { return name + "-windows.out" } return name + ".out" } func removeSummaryTime(t *testing.T, r io.Reader) string { t.Helper() out := new(strings.Builder) scan := bufio.NewScanner(r) for scan.Scan() { line := scan.Text() if i := strings.Index(line, " in "); i > 0 { out.WriteString(line[:i] + "\n") continue } out.WriteString(line + "\n") } assert.NilError(t, scan.Err()) return out.String() } func TestFmtDotElapsed(t *testing.T) { var testcases = []struct { cached bool elapsed time.Duration expected string }{ { elapsed: 999 * time.Microsecond, expected: " 999µs ", }, { elapsed: 7 * time.Millisecond, expected: " 7ms ", }, { cached: true, elapsed: time.Millisecond, expected: " 🖴 ", }, { elapsed: 3 * time.Hour, expected: " ⏳ ", }, { elapsed: 14 * time.Millisecond, expected: " 14ms ", }, { elapsed: 333 * time.Millisecond, expected: " 333ms ", }, { elapsed: 1337 * time.Millisecond, expected: " 1.33s ", }, { elapsed: 14821 * time.Millisecond, expected: " 14.8s ", }, { elapsed: time.Minute + 59*time.Second, expected: " 1m59s ", }, { elapsed: 59*time.Minute + 59*time.Second, expected: " 59m0s ", }, { elapsed: 148213 * time.Millisecond, expected: " 2m28s ", }, { elapsed: 1482137 * time.Millisecond, expected: " 24m0s ", }, } for _, tc := range testcases { t.Run(tc.expected, func(t *testing.T) { pkg := &Package{ cached: tc.cached, Passed: []TestCase{{Elapsed: tc.elapsed}}, } actual := fmtDotElapsed(pkg) assert.Check(t, cmp.Equal(utf8.RuneCountInString(actual), 7)) assert.Equal(t, actual, tc.expected) }) } } func TestFm
sting.T) { f := func(d time.Duration) bool { pkg := &Package{ Passed: []TestCase{{Elapsed: d}}, } actual := fmtDotElapsed(pkg) width := utf8.RuneCountInString(actual) if width == 7 { return true } t.Logf("actual %v (width %d)", actual, width) return false } seed := time.Now().Unix() t.Log("seed", seed) assert.Assert(t, quick.Check(f, &quick.Config{ MaxCountScale: 2000, Rand: rand.New(rand.NewSource(seed)), })) } func TestNewDotFormatter(t *testing.T) { buf := new(bytes.Buffer) ef := newDotFormatter(buf) d, ok := ef.(*dotFormatter) skip.If(t, !ok, "no terminal width") assert.Assert(t, d.termWidth != 0) }
tDotElapsed_RuneCountProperty(t *te
typemeta.go
/* Copyright 2019 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package lib import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "knative.dev/eventing/test/lib/resources" ) // SubscriptionTypeMeta is the TypeMeta ref for Subscription. var SubscriptionTypeMeta = MessagingTypeMeta(resources.SubscriptionKind) // BrokerTypeMeta is the TypeMeta ref for Broker. var BrokerTypeMeta = EventingTypeMeta(resources.BrokerKind) // TriggerTypeMeta is the TypeMeta ref for Trigger. var TriggerTypeMeta = EventingTypeMeta(resources.TriggerKind) // EventingTypeMeta returns the TypeMeta ref for an eventing resource. func EventingTypeMeta(kind string) *metav1.TypeMeta { return &metav1.TypeMeta{ Kind: kind, APIVersion: resources.EventingAPIVersion, } } // ChannelTypeMeta is the TypeMeta ref for Channel. var ChannelTypeMeta = MessagingTypeMeta(resources.ChannelKind) // SequenceTypeMeta is the TypeMeta ref for Sequence.
// ParallelTypeMeta is the TypeMeta ref for Parallel. var ParallelTypeMeta = MessagingTypeMeta(resources.ParallelKind) // MessagingTypeMeta returns the TypeMeta ref for an eventing messaging resource. func MessagingTypeMeta(kind string) *metav1.TypeMeta { return &metav1.TypeMeta{ Kind: kind, APIVersion: resources.MessagingAPIVersion, } } // FlowsParallelTypeMeta is the TypeMeta ref for Parallel (in flows.knative.dev). var FlowsParallelTypeMeta = FlowsTypeMeta(resources.FlowsParallelKind) // FlowsSequenceTypeMeta is the TypeMeta ref for Sequence (in flows.knative.dev). var FlowsSequenceTypeMeta = FlowsTypeMeta(resources.FlowsSequenceKind) // FlowsTypeMeta returns the TypeMeta ref for an eventing messaing resource. func FlowsTypeMeta(kind string) *metav1.TypeMeta { return &metav1.TypeMeta{ Kind: kind, APIVersion: resources.FlowsAPIVersion, } }
var SequenceTypeMeta = MessagingTypeMeta(resources.SequenceKind)
go117_export.go
// export by github.com/goplus/gossa/cmd/qexp //go:build go1.17 && !go1.18 // +build go1.17,!go1.18 package rc4 import ( q "crypto/rc4" "reflect" "github.com/goplus/gossa" ) func
() { gossa.RegisterPackage(&gossa.Package{ Name: "rc4", Path: "crypto/rc4", Deps: map[string]string{ "crypto/internal/subtle": "subtle", "strconv": "strconv", }, Interfaces: map[string]reflect.Type{}, NamedTypes: map[string]gossa.NamedType{ "Cipher": {reflect.TypeOf((*q.Cipher)(nil)).Elem(), "", "Reset,XORKeyStream"}, "KeySizeError": {reflect.TypeOf((*q.KeySizeError)(nil)).Elem(), "Error", ""}, }, AliasTypes: map[string]reflect.Type{}, Vars: map[string]reflect.Value{}, Funcs: map[string]reflect.Value{ "NewCipher": reflect.ValueOf(q.NewCipher), }, TypedConsts: map[string]gossa.TypedConst{}, UntypedConsts: map[string]gossa.UntypedConst{}, }) }
init
protos.d.ts
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as Long from "long"; import * as $protobuf from "protobufjs"; /** Namespace google. */ export namespace google { /** Namespace protobuf. */ namespace protobuf { /** Properties of a Duration. */ interface IDuration { /** Duration seconds */ seconds?: (number|Long|string|null); /** Duration nanos */ nanos?: (number|null); } /** Represents a Duration. */ class Duration implements IDuration { /** * Constructs a new Duration. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IDuration); /** Duration seconds. */ public seconds: (number|Long|string); /** Duration nanos. */ public nanos: number; /** * Creates a new Duration instance using the specified properties. * @param [properties] Properties to set * @returns Duration instance */ public static create(properties?: google.protobuf.IDuration): google.protobuf.Duration; /** * Encodes the specified Duration message. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. * @param message Duration message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Duration message, length delimited. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. * @param message Duration message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IDuration, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Duration message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Duration * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Duration; /** * Decodes a Duration message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Duration * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Duration; /** * Verifies a Duration message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Duration message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Duration */ public static fromObject(object: { [k: string]: any }): google.protobuf.Duration; /** * Creates a plain object from a Duration message. Also converts values to other types if specified. * @param message Duration * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Duration, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Duration to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FileDescriptorSet. */ interface IFileDescriptorSet { /** FileDescriptorSet file */ file?: (google.protobuf.IFileDescriptorProto[]|null); } /** Represents a FileDescriptorSet. */ class FileDescriptorSet implements IFileDescriptorSet { /** * Constructs a new FileDescriptorSet. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFileDescriptorSet); /** FileDescriptorSet file. */ public file: google.protobuf.IFileDescriptorProto[]; /** * Creates a new FileDescriptorSet instance using the specified properties. * @param [properties] Properties to set * @returns FileDescriptorSet instance */ public static create(properties?: google.protobuf.IFileDescriptorSet): google.protobuf.FileDescriptorSet; /** * Encodes the specified FileDescriptorSet message. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. * @param message FileDescriptorSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FileDescriptorSet message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorSet.verify|verify} messages. * @param message FileDescriptorSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFileDescriptorSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FileDescriptorSet message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FileDescriptorSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorSet; /** * Decodes a FileDescriptorSet message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FileDescriptorSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorSet; /** * Verifies a FileDescriptorSet message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FileDescriptorSet message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FileDescriptorSet */ public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorSet; /** * Creates a plain object from a FileDescriptorSet message. Also converts values to other types if specified. * @param message FileDescriptorSet * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FileDescriptorSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FileDescriptorSet to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FileDescriptorProto. */ interface IFileDescriptorProto { /** FileDescriptorProto name */ name?: (string|null); /** FileDescriptorProto package */ "package"?: (string|null); /** FileDescriptorProto dependency */ dependency?: (string[]|null); /** FileDescriptorProto publicDependency */ publicDependency?: (number[]|null); /** FileDescriptorProto weakDependency */ weakDependency?: (number[]|null); /** FileDescriptorProto messageType */ messageType?: (google.protobuf.IDescriptorProto[]|null); /** FileDescriptorProto enumType */ enumType?: (google.protobuf.IEnumDescriptorProto[]|null); /** FileDescriptorProto service */ service?: (google.protobuf.IServiceDescriptorProto[]|null); /** FileDescriptorProto extension */ extension?: (google.protobuf.IFieldDescriptorProto[]|null); /** FileDescriptorProto options */ options?: (google.protobuf.IFileOptions|null); /** FileDescriptorProto sourceCodeInfo */ sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); /** FileDescriptorProto syntax */ syntax?: (string|null); } /** Represents a FileDescriptorProto. */ class FileDescriptorProto implements IFileDescriptorProto { /** * Constructs a new FileDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFileDescriptorProto); /** FileDescriptorProto name. */ public name: string; /** FileDescriptorProto package. */ public package: string; /** FileDescriptorProto dependency. */ public dependency: string[]; /** FileDescriptorProto publicDependency. */ public publicDependency: number[]; /** FileDescriptorProto weakDependency. */ public weakDependency: number[]; /** FileDescriptorProto messageType. */ public messageType: google.protobuf.IDescriptorProto[]; /** FileDescriptorProto enumType. */ public enumType: google.protobuf.IEnumDescriptorProto[]; /** FileDescriptorProto service. */ public service: google.protobuf.IServiceDescriptorProto[]; /** FileDescriptorProto extension. */ public extension: google.protobuf.IFieldDescriptorProto[]; /** FileDescriptorProto options. */ public options?: (google.protobuf.IFileOptions|null); /** FileDescriptorProto sourceCodeInfo. */ public sourceCodeInfo?: (google.protobuf.ISourceCodeInfo|null); /** FileDescriptorProto syntax. */ public syntax: string; /** * Creates a new FileDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns FileDescriptorProto instance */ public static create(properties?: google.protobuf.IFileDescriptorProto): google.protobuf.FileDescriptorProto; /** * Encodes the specified FileDescriptorProto message. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. * @param message FileDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FileDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FileDescriptorProto.verify|verify} messages. * @param message FileDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFileDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FileDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FileDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileDescriptorProto; /** * Decodes a FileDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FileDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileDescriptorProto; /** * Verifies a FileDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FileDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FileDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.FileDescriptorProto; /** * Creates a plain object from a FileDescriptorProto message. Also converts values to other types if specified. * @param message FileDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FileDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FileDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DescriptorProto. */ interface IDescriptorProto { /** DescriptorProto name */ name?: (string|null); /** DescriptorProto field */ field?: (google.protobuf.IFieldDescriptorProto[]|null); /** DescriptorProto extension */ extension?: (google.protobuf.IFieldDescriptorProto[]|null); /** DescriptorProto nestedType */ nestedType?: (google.protobuf.IDescriptorProto[]|null); /** DescriptorProto enumType */ enumType?: (google.protobuf.IEnumDescriptorProto[]|null); /** DescriptorProto extensionRange */ extensionRange?: (google.protobuf.DescriptorProto.IExtensionRange[]|null); /** DescriptorProto oneofDecl */ oneofDecl?: (google.protobuf.IOneofDescriptorProto[]|null); /** DescriptorProto options */ options?: (google.protobuf.IMessageOptions|null); /** DescriptorProto reservedRange */ reservedRange?: (google.protobuf.DescriptorProto.IReservedRange[]|null); /** DescriptorProto reservedName */ reservedName?: (string[]|null); } /** Represents a DescriptorProto. */ class DescriptorProto implements IDescriptorProto { /** * Constructs a new DescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IDescriptorProto); /** DescriptorProto name. */ public name: string; /** DescriptorProto field. */ public field: google.protobuf.IFieldDescriptorProto[]; /** DescriptorProto extension. */ public extension: google.protobuf.IFieldDescriptorProto[]; /** DescriptorProto nestedType. */ public nestedType: google.protobuf.IDescriptorProto[]; /** DescriptorProto enumType. */ public enumType: google.protobuf.IEnumDescriptorProto[]; /** DescriptorProto extensionRange. */ public extensionRange: google.protobuf.DescriptorProto.IExtensionRange[]; /** DescriptorProto oneofDecl. */ public oneofDecl: google.protobuf.IOneofDescriptorProto[]; /** DescriptorProto options. */ public options?: (google.protobuf.IMessageOptions|null); /** DescriptorProto reservedRange. */ public reservedRange: google.protobuf.DescriptorProto.IReservedRange[]; /** DescriptorProto reservedName. */ public reservedName: string[]; /** * Creates a new DescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns DescriptorProto instance */ public static create(properties?: google.protobuf.IDescriptorProto): google.protobuf.DescriptorProto; /** * Encodes the specified DescriptorProto message. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. * @param message DescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.verify|verify} messages. * @param message DescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto; /** * Decodes a DescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto; /** * Verifies a DescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto; /** * Creates a plain object from a DescriptorProto message. Also converts values to other types if specified. * @param message DescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.DescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace DescriptorProto { /** Properties of an ExtensionRange. */ interface IExtensionRange { /** ExtensionRange start */ start?: (number|null); /** ExtensionRange end */ end?: (number|null); /** ExtensionRange options */ options?: (google.protobuf.IExtensionRangeOptions|null); } /** Represents an ExtensionRange. */ class ExtensionRange implements IExtensionRange { /** * Constructs a new ExtensionRange. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.DescriptorProto.IExtensionRange); /** ExtensionRange start. */ public start: number; /** ExtensionRange end. */ public end: number; /** ExtensionRange options. */ public options?: (google.protobuf.IExtensionRangeOptions|null); /** * Creates a new ExtensionRange instance using the specified properties. * @param [properties] Properties to set * @returns ExtensionRange instance */ public static create(properties?: google.protobuf.DescriptorProto.IExtensionRange): google.protobuf.DescriptorProto.ExtensionRange; /** * Encodes the specified ExtensionRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. * @param message ExtensionRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExtensionRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ExtensionRange.verify|verify} messages. * @param message ExtensionRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.DescriptorProto.IExtensionRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExtensionRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExtensionRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ExtensionRange; /** * Decodes an ExtensionRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExtensionRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ExtensionRange; /** * Verifies an ExtensionRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExtensionRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExtensionRange */ public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ExtensionRange; /** * Creates a plain object from an ExtensionRange message. Also converts values to other types if specified. * @param message ExtensionRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.DescriptorProto.ExtensionRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExtensionRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ReservedRange. */ interface IReservedRange { /** ReservedRange start */ start?: (number|null); /** ReservedRange end */ end?: (number|null); } /** Represents a ReservedRange. */ class ReservedRange implements IReservedRange { /** * Constructs a new ReservedRange. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.DescriptorProto.IReservedRange); /** ReservedRange start. */ public start: number; /** ReservedRange end. */ public end: number; /** * Creates a new ReservedRange instance using the specified properties. * @param [properties] Properties to set * @returns ReservedRange instance */ public static create(properties?: google.protobuf.DescriptorProto.IReservedRange): google.protobuf.DescriptorProto.ReservedRange; /** * Encodes the specified ReservedRange message. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. * @param message ReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ReservedRange message, length delimited. Does not implicitly {@link google.protobuf.DescriptorProto.ReservedRange.verify|verify} messages. * @param message ReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.DescriptorProto.IReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ReservedRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.DescriptorProto.ReservedRange; /** * Decodes a ReservedRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.DescriptorProto.ReservedRange; /** * Verifies a ReservedRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ReservedRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ReservedRange */ public static fromObject(object: { [k: string]: any }): google.protobuf.DescriptorProto.ReservedRange; /** * Creates a plain object from a ReservedRange message. Also converts values to other types if specified. * @param message ReservedRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.DescriptorProto.ReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ReservedRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of an ExtensionRangeOptions. */ interface IExtensionRangeOptions { /** ExtensionRangeOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an ExtensionRangeOptions. */ class ExtensionRangeOptions implements IExtensionRangeOptions { /** * Constructs a new ExtensionRangeOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IExtensionRangeOptions); /** ExtensionRangeOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new ExtensionRangeOptions instance using the specified properties. * @param [properties] Properties to set * @returns ExtensionRangeOptions instance */ public static create(properties?: google.protobuf.IExtensionRangeOptions): google.protobuf.ExtensionRangeOptions; /** * Encodes the specified ExtensionRangeOptions message. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. * @param message ExtensionRangeOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExtensionRangeOptions message, length delimited. Does not implicitly {@link google.protobuf.ExtensionRangeOptions.verify|verify} messages. * @param message ExtensionRangeOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IExtensionRangeOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExtensionRangeOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExtensionRangeOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ExtensionRangeOptions; /** * Decodes an ExtensionRangeOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExtensionRangeOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ExtensionRangeOptions; /** * Verifies an ExtensionRangeOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExtensionRangeOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExtensionRangeOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.ExtensionRangeOptions; /** * Creates a plain object from an ExtensionRangeOptions message. Also converts values to other types if specified. * @param message ExtensionRangeOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ExtensionRangeOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExtensionRangeOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FieldDescriptorProto. */ interface IFieldDescriptorProto { /** FieldDescriptorProto name */ name?: (string|null); /** FieldDescriptorProto number */ number?: (number|null); /** FieldDescriptorProto label */ label?: (google.protobuf.FieldDescriptorProto.Label|keyof typeof google.protobuf.FieldDescriptorProto.Label|null); /** FieldDescriptorProto type */ type?: (google.protobuf.FieldDescriptorProto.Type|keyof typeof google.protobuf.FieldDescriptorProto.Type|null); /** FieldDescriptorProto typeName */ typeName?: (string|null); /** FieldDescriptorProto extendee */ extendee?: (string|null); /** FieldDescriptorProto defaultValue */ defaultValue?: (string|null); /** FieldDescriptorProto oneofIndex */ oneofIndex?: (number|null); /** FieldDescriptorProto jsonName */ jsonName?: (string|null); /** FieldDescriptorProto options */ options?: (google.protobuf.IFieldOptions|null); } /** Represents a FieldDescriptorProto. */ class FieldDescriptorProto implements IFieldDescriptorProto { /** * Constructs a new FieldDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFieldDescriptorProto); /** FieldDescriptorProto name. */ public name: string; /** FieldDescriptorProto number. */ public number: number; /** FieldDescriptorProto label. */ public label: (google.protobuf.FieldDescriptorProto.Label|keyof typeof google.protobuf.FieldDescriptorProto.Label); /** FieldDescriptorProto type. */ public type: (google.protobuf.FieldDescriptorProto.Type|keyof typeof google.protobuf.FieldDescriptorProto.Type); /** FieldDescriptorProto typeName. */ public typeName: string; /** FieldDescriptorProto extendee. */ public extendee: string; /** FieldDescriptorProto defaultValue. */ public defaultValue: string; /** FieldDescriptorProto oneofIndex. */ public oneofIndex: number; /** FieldDescriptorProto jsonName. */ public jsonName: string; /** FieldDescriptorProto options. */ public options?: (google.protobuf.IFieldOptions|null); /** * Creates a new FieldDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns FieldDescriptorProto instance */ public static create(properties?: google.protobuf.IFieldDescriptorProto): google.protobuf.FieldDescriptorProto; /** * Encodes the specified FieldDescriptorProto message. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. * @param message FieldDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FieldDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.FieldDescriptorProto.verify|verify} messages. * @param message FieldDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFieldDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FieldDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FieldDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldDescriptorProto; /** * Decodes a FieldDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FieldDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldDescriptorProto; /** * Verifies a FieldDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FieldDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FieldDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.FieldDescriptorProto; /** * Creates a plain object from a FieldDescriptorProto message. Also converts values to other types if specified. * @param message FieldDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FieldDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FieldDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace FieldDescriptorProto { /** Type enum. */ enum Type { TYPE_DOUBLE = 1, TYPE_FLOAT = 2, TYPE_INT64 = 3, TYPE_UINT64 = 4, TYPE_INT32 = 5, TYPE_FIXED64 = 6, TYPE_FIXED32 = 7, TYPE_BOOL = 8, TYPE_STRING = 9, TYPE_GROUP = 10, TYPE_MESSAGE = 11, TYPE_BYTES = 12, TYPE_UINT32 = 13, TYPE_ENUM = 14, TYPE_SFIXED32 = 15, TYPE_SFIXED64 = 16, TYPE_SINT32 = 17, TYPE_SINT64 = 18 } /** Label enum. */ enum Label { LABEL_OPTIONAL = 1, LABEL_REQUIRED = 2, LABEL_REPEATED = 3 } } /** Properties of an OneofDescriptorProto. */ interface IOneofDescriptorProto { /** OneofDescriptorProto name */ name?: (string|null); /** OneofDescriptorProto options */ options?: (google.protobuf.IOneofOptions|null); } /** Represents an OneofDescriptorProto. */ class OneofDescriptorProto implements IOneofDescriptorProto { /** * Constructs a new OneofDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IOneofDescriptorProto); /** OneofDescriptorProto name. */ public name: string; /** OneofDescriptorProto options. */ public options?: (google.protobuf.IOneofOptions|null); /** * Creates a new OneofDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns OneofDescriptorProto instance */ public static create(properties?: google.protobuf.IOneofDescriptorProto): google.protobuf.OneofDescriptorProto; /** * Encodes the specified OneofDescriptorProto message. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. * @param message OneofDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OneofDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.OneofDescriptorProto.verify|verify} messages. * @param message OneofDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IOneofDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OneofDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OneofDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofDescriptorProto; /** * Decodes an OneofDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OneofDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofDescriptorProto; /** * Verifies an OneofDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OneofDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OneofDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.OneofDescriptorProto; /** * Creates a plain object from an OneofDescriptorProto message. Also converts values to other types if specified. * @param message OneofDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.OneofDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OneofDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an EnumDescriptorProto. */ interface IEnumDescriptorProto { /** EnumDescriptorProto name */ name?: (string|null); /** EnumDescriptorProto value */ value?: (google.protobuf.IEnumValueDescriptorProto[]|null); /** EnumDescriptorProto options */ options?: (google.protobuf.IEnumOptions|null); /** EnumDescriptorProto reservedRange */ reservedRange?: (google.protobuf.EnumDescriptorProto.IEnumReservedRange[]|null); /** EnumDescriptorProto reservedName */ reservedName?: (string[]|null); } /** Represents an EnumDescriptorProto. */ class EnumDescriptorProto implements IEnumDescriptorProto { /** * Constructs a new EnumDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumDescriptorProto); /** EnumDescriptorProto name. */ public name: string; /** EnumDescriptorProto value. */ public value: google.protobuf.IEnumValueDescriptorProto[]; /** EnumDescriptorProto options. */ public options?: (google.protobuf.IEnumOptions|null); /** EnumDescriptorProto reservedRange. */ public reservedRange: google.protobuf.EnumDescriptorProto.IEnumReservedRange[]; /** EnumDescriptorProto reservedName. */ public reservedName: string[]; /** * Creates a new EnumDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns EnumDescriptorProto instance */ public static create(properties?: google.protobuf.IEnumDescriptorProto): google.protobuf.EnumDescriptorProto; /** * Encodes the specified EnumDescriptorProto message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. * @param message EnumDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.verify|verify} messages. * @param message EnumDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto; /** * Decodes an EnumDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto; /** * Verifies an EnumDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto; /** * Creates a plain object from an EnumDescriptorProto message. Also converts values to other types if specified. * @param message EnumDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace EnumDescriptorProto { /** Properties of an EnumReservedRange. */ interface IEnumReservedRange { /** EnumReservedRange start */ start?: (number|null); /** EnumReservedRange end */ end?: (number|null); } /** Represents an EnumReservedRange. */ class EnumReservedRange implements IEnumReservedRange { /** * Constructs a new EnumReservedRange. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange); /** EnumReservedRange start. */ public start: number; /** EnumReservedRange end. */ public end: number; /** * Creates a new EnumReservedRange instance using the specified properties. * @param [properties] Properties to set * @returns EnumReservedRange instance */ public static create(properties?: google.protobuf.EnumDescriptorProto.IEnumReservedRange): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Encodes the specified EnumReservedRange message. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. * @param message EnumReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumReservedRange message, length delimited. Does not implicitly {@link google.protobuf.EnumDescriptorProto.EnumReservedRange.verify|verify} messages. * @param message EnumReservedRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.EnumDescriptorProto.IEnumReservedRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumReservedRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Decodes an EnumReservedRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumReservedRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Verifies an EnumReservedRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumReservedRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumReservedRange */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumDescriptorProto.EnumReservedRange; /** * Creates a plain object from an EnumReservedRange message. Also converts values to other types if specified. * @param message EnumReservedRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumDescriptorProto.EnumReservedRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumReservedRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of an EnumValueDescriptorProto. */ interface IEnumValueDescriptorProto { /** EnumValueDescriptorProto name */ name?: (string|null); /** EnumValueDescriptorProto number */ number?: (number|null); /** EnumValueDescriptorProto options */ options?: (google.protobuf.IEnumValueOptions|null); } /** Represents an EnumValueDescriptorProto. */ class EnumValueDescriptorProto implements IEnumValueDescriptorProto { /** * Constructs a new EnumValueDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumValueDescriptorProto); /** EnumValueDescriptorProto name. */ public name: string; /** EnumValueDescriptorProto number. */ public number: number; /** EnumValueDescriptorProto options. */ public options?: (google.protobuf.IEnumValueOptions|null); /** * Creates a new EnumValueDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns EnumValueDescriptorProto instance */ public static create(properties?: google.protobuf.IEnumValueDescriptorProto): google.protobuf.EnumValueDescriptorProto; /** * Encodes the specified EnumValueDescriptorProto message. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. * @param message EnumValueDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumValueDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.EnumValueDescriptorProto.verify|verify} messages. * @param message EnumValueDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumValueDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumValueDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumValueDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueDescriptorProto; /** * Decodes an EnumValueDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumValueDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueDescriptorProto; /** * Verifies an EnumValueDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumValueDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumValueDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueDescriptorProto; /** * Creates a plain object from an EnumValueDescriptorProto message. Also converts values to other types if specified. * @param message EnumValueDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumValueDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumValueDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ServiceDescriptorProto. */ interface IServiceDescriptorProto { /** ServiceDescriptorProto name */ name?: (string|null); /** ServiceDescriptorProto method */ method?: (google.protobuf.IMethodDescriptorProto[]|null); /** ServiceDescriptorProto options */ options?: (google.protobuf.IServiceOptions|null); } /** Represents a ServiceDescriptorProto. */ class ServiceDescriptorProto implements IServiceDescriptorProto { /** * Constructs a new ServiceDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IServiceDescriptorProto); /** ServiceDescriptorProto name. */ public name: string; /** ServiceDescriptorProto method. */ public method: google.protobuf.IMethodDescriptorProto[]; /** ServiceDescriptorProto options. */ public options?: (google.protobuf.IServiceOptions|null); /** * Creates a new ServiceDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns ServiceDescriptorProto instance */ public static create(properties?: google.protobuf.IServiceDescriptorProto): google.protobuf.ServiceDescriptorProto; /** * Encodes the specified ServiceDescriptorProto message. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. * @param message ServiceDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ServiceDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.ServiceDescriptorProto.verify|verify} messages. * @param message ServiceDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IServiceDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ServiceDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ServiceDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceDescriptorProto; /** * Decodes a ServiceDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ServiceDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceDescriptorProto; /** * Verifies a ServiceDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ServiceDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ServiceDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceDescriptorProto; /** * Creates a plain object from a ServiceDescriptorProto message. Also converts values to other types if specified. * @param message ServiceDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ServiceDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ServiceDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MethodDescriptorProto. */ interface IMethodDescriptorProto { /** MethodDescriptorProto name */ name?: (string|null); /** MethodDescriptorProto inputType */ inputType?: (string|null); /** MethodDescriptorProto outputType */ outputType?: (string|null); /** MethodDescriptorProto options */ options?: (google.protobuf.IMethodOptions|null); /** MethodDescriptorProto clientStreaming */ clientStreaming?: (boolean|null); /** MethodDescriptorProto serverStreaming */ serverStreaming?: (boolean|null); } /** Represents a MethodDescriptorProto. */ class MethodDescriptorProto implements IMethodDescriptorProto { /** * Constructs a new MethodDescriptorProto. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IMethodDescriptorProto); /** MethodDescriptorProto name. */ public name: string; /** MethodDescriptorProto inputType. */ public inputType: string; /** MethodDescriptorProto outputType. */ public outputType: string; /** MethodDescriptorProto options. */ public options?: (google.protobuf.IMethodOptions|null); /** MethodDescriptorProto clientStreaming. */ public clientStreaming: boolean; /** MethodDescriptorProto serverStreaming. */ public serverStreaming: boolean; /** * Creates a new MethodDescriptorProto instance using the specified properties. * @param [properties] Properties to set * @returns MethodDescriptorProto instance */ public static create(properties?: google.protobuf.IMethodDescriptorProto): google.protobuf.MethodDescriptorProto; /** * Encodes the specified MethodDescriptorProto message. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. * @param message MethodDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MethodDescriptorProto message, length delimited. Does not implicitly {@link google.protobuf.MethodDescriptorProto.verify|verify} messages. * @param message MethodDescriptorProto message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IMethodDescriptorProto, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MethodDescriptorProto message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MethodDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodDescriptorProto; /** * Decodes a MethodDescriptorProto message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MethodDescriptorProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodDescriptorProto; /** * Verifies a MethodDescriptorProto message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MethodDescriptorProto message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MethodDescriptorProto */ public static fromObject(object: { [k: string]: any }): google.protobuf.MethodDescriptorProto; /** * Creates a plain object from a MethodDescriptorProto message. Also converts values to other types if specified. * @param message MethodDescriptorProto * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.MethodDescriptorProto, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MethodDescriptorProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FileOptions. */ interface IFileOptions { /** FileOptions javaPackage */ javaPackage?: (string|null); /** FileOptions javaOuterClassname */ javaOuterClassname?: (string|null); /** FileOptions javaMultipleFiles */ javaMultipleFiles?: (boolean|null); /** FileOptions javaGenerateEqualsAndHash */ javaGenerateEqualsAndHash?: (boolean|null); /** FileOptions javaStringCheckUtf8 */ javaStringCheckUtf8?: (boolean|null); /** FileOptions optimizeFor */ optimizeFor?: (google.protobuf.FileOptions.OptimizeMode|keyof typeof google.protobuf.FileOptions.OptimizeMode|null); /** FileOptions goPackage */ goPackage?: (string|null); /** FileOptions ccGenericServices */ ccGenericServices?: (boolean|null); /** FileOptions javaGenericServices */ javaGenericServices?: (boolean|null); /** FileOptions pyGenericServices */ pyGenericServices?: (boolean|null); /** FileOptions phpGenericServices */ phpGenericServices?: (boolean|null); /** FileOptions deprecated */ deprecated?: (boolean|null); /** FileOptions ccEnableArenas */ ccEnableArenas?: (boolean|null); /** FileOptions objcClassPrefix */ objcClassPrefix?: (string|null); /** FileOptions csharpNamespace */ csharpNamespace?: (string|null); /** FileOptions swiftPrefix */ swiftPrefix?: (string|null); /** FileOptions phpClassPrefix */ phpClassPrefix?: (string|null); /** FileOptions phpNamespace */ phpNamespace?: (string|null); /** FileOptions phpMetadataNamespace */ phpMetadataNamespace?: (string|null); /** FileOptions rubyPackage */ rubyPackage?: (string|null); /** FileOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); /** FileOptions .google.api.resourceDefinition */ ".google.api.resourceDefinition"?: (google.api.IResourceDescriptor[]|null); } /** Represents a FileOptions. */ class FileOptions implements IFileOptions { /** * Constructs a new FileOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFileOptions); /** FileOptions javaPackage. */ public javaPackage: string; /** FileOptions javaOuterClassname. */ public javaOuterClassname: string; /** FileOptions javaMultipleFiles. */ public javaMultipleFiles: boolean; /** FileOptions javaGenerateEqualsAndHash. */ public javaGenerateEqualsAndHash: boolean; /** FileOptions javaStringCheckUtf8. */ public javaStringCheckUtf8: boolean; /** FileOptions optimizeFor. */ public optimizeFor: (google.protobuf.FileOptions.OptimizeMode|keyof typeof google.protobuf.FileOptions.OptimizeMode); /** FileOptions goPackage. */ public goPackage: string; /** FileOptions ccGenericServices. */ public ccGenericServices: boolean; /** FileOptions javaGenericServices. */ public javaGenericServices: boolean; /** FileOptions pyGenericServices. */ public pyGenericServices: boolean; /** FileOptions phpGenericServices. */ public phpGenericServices: boolean; /** FileOptions deprecated. */ public deprecated: boolean; /** FileOptions ccEnableArenas. */ public ccEnableArenas: boolean; /** FileOptions objcClassPrefix. */ public objcClassPrefix: string; /** FileOptions csharpNamespace. */ public csharpNamespace: string; /** FileOptions swiftPrefix. */ public swiftPrefix: string; /** FileOptions phpClassPrefix. */ public phpClassPrefix: string; /** FileOptions phpNamespace. */ public phpNamespace: string; /** FileOptions phpMetadataNamespace. */ public phpMetadataNamespace: string; /** FileOptions rubyPackage. */ public rubyPackage: string; /** FileOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new FileOptions instance using the specified properties. * @param [properties] Properties to set * @returns FileOptions instance */ public static create(properties?: google.protobuf.IFileOptions): google.protobuf.FileOptions; /** * Encodes the specified FileOptions message. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. * @param message FileOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FileOptions message, length delimited. Does not implicitly {@link google.protobuf.FileOptions.verify|verify} messages. * @param message FileOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFileOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FileOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FileOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FileOptions; /** * Decodes a FileOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FileOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FileOptions; /** * Verifies a FileOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FileOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FileOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.FileOptions; /** * Creates a plain object from a FileOptions message. Also converts values to other types if specified. * @param message FileOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FileOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FileOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace FileOptions { /** OptimizeMode enum. */ enum OptimizeMode { SPEED = 1, CODE_SIZE = 2, LITE_RUNTIME = 3 } } /** Properties of a MessageOptions. */ interface IMessageOptions { /** MessageOptions messageSetWireFormat */ messageSetWireFormat?: (boolean|null); /** MessageOptions noStandardDescriptorAccessor */ noStandardDescriptorAccessor?: (boolean|null); /** MessageOptions deprecated */ deprecated?: (boolean|null); /** MessageOptions mapEntry */ mapEntry?: (boolean|null); /** MessageOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); /** MessageOptions .google.api.resource */ ".google.api.resource"?: (google.api.IResourceDescriptor|null); } /** Represents a MessageOptions. */ class MessageOptions implements IMessageOptions { /** * Constructs a new MessageOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IMessageOptions); /** MessageOptions messageSetWireFormat. */ public messageSetWireFormat: boolean; /** MessageOptions noStandardDescriptorAccessor. */ public noStandardDescriptorAccessor: boolean; /** MessageOptions deprecated. */ public deprecated: boolean; /** MessageOptions mapEntry. */ public mapEntry: boolean; /** MessageOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new MessageOptions instance using the specified properties. * @param [properties] Properties to set * @returns MessageOptions instance */ public static create(properties?: google.protobuf.IMessageOptions): google.protobuf.MessageOptions; /** * Encodes the specified MessageOptions message. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. * @param message MessageOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MessageOptions message, length delimited. Does not implicitly {@link google.protobuf.MessageOptions.verify|verify} messages. * @param message MessageOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IMessageOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MessageOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MessageOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MessageOptions; /** * Decodes a MessageOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MessageOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MessageOptions; /** * Verifies a MessageOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MessageOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MessageOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.MessageOptions; /** * Creates a plain object from a MessageOptions message. Also converts values to other types if specified. * @param message MessageOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.MessageOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MessageOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FieldOptions. */ interface IFieldOptions { /** FieldOptions ctype */ ctype?: (google.protobuf.FieldOptions.CType|keyof typeof google.protobuf.FieldOptions.CType|null); /** FieldOptions packed */ packed?: (boolean|null); /** FieldOptions jstype */ jstype?: (google.protobuf.FieldOptions.JSType|keyof typeof google.protobuf.FieldOptions.JSType|null); /** FieldOptions lazy */ lazy?: (boolean|null); /** FieldOptions deprecated */ deprecated?: (boolean|null); /** FieldOptions weak */ weak?: (boolean|null); /** FieldOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); /** FieldOptions .google.api.fieldBehavior */ ".google.api.fieldBehavior"?: (google.api.FieldBehavior[]|null); /** FieldOptions .google.api.resourceReference */ ".google.api.resourceReference"?: (google.api.IResourceReference|null); } /** Represents a FieldOptions. */ class FieldOptions implements IFieldOptions { /** * Constructs a new FieldOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFieldOptions); /** FieldOptions ctype. */ public ctype: (google.protobuf.FieldOptions.CType|keyof typeof google.protobuf.FieldOptions.CType); /** FieldOptions packed. */ public packed: boolean; /** FieldOptions jstype. */ public jstype: (google.protobuf.FieldOptions.JSType|keyof typeof google.protobuf.FieldOptions.JSType); /** FieldOptions lazy. */ public lazy: boolean; /** FieldOptions deprecated. */ public deprecated: boolean; /** FieldOptions weak. */ public weak: boolean; /** FieldOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new FieldOptions instance using the specified properties. * @param [properties] Properties to set * @returns FieldOptions instance */ public static create(properties?: google.protobuf.IFieldOptions): google.protobuf.FieldOptions; /** * Encodes the specified FieldOptions message. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. * @param message FieldOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FieldOptions message, length delimited. Does not implicitly {@link google.protobuf.FieldOptions.verify|verify} messages. * @param message FieldOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFieldOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FieldOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FieldOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldOptions; /** * Decodes a FieldOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FieldOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldOptions; /** * Verifies a FieldOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FieldOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FieldOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.FieldOptions; /** * Creates a plain object from a FieldOptions message. Also converts values to other types if specified. * @param message FieldOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FieldOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FieldOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace FieldOptions { /** CType enum. */ enum CType { STRING = 0, CORD = 1, STRING_PIECE = 2 } /** JSType enum. */ enum JSType { JS_NORMAL = 0, JS_STRING = 1, JS_NUMBER = 2 } } /** Properties of an OneofOptions. */ interface IOneofOptions { /** OneofOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an OneofOptions. */ class OneofOptions implements IOneofOptions { /** * Constructs a new OneofOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IOneofOptions); /** OneofOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new OneofOptions instance using the specified properties. * @param [properties] Properties to set * @returns OneofOptions instance */ public static create(properties?: google.protobuf.IOneofOptions): google.protobuf.OneofOptions; /** * Encodes the specified OneofOptions message. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. * @param message OneofOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OneofOptions message, length delimited. Does not implicitly {@link google.protobuf.OneofOptions.verify|verify} messages. * @param message OneofOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IOneofOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OneofOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OneofOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.OneofOptions; /** * Decodes an OneofOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OneofOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.OneofOptions; /** * Verifies an OneofOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OneofOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OneofOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.OneofOptions; /** * Creates a plain object from an OneofOptions message. Also converts values to other types if specified. * @param message OneofOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.OneofOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OneofOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an EnumOptions. */ interface IEnumOptions { /** EnumOptions allowAlias */ allowAlias?: (boolean|null); /** EnumOptions deprecated */ deprecated?: (boolean|null); /** EnumOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an EnumOptions. */ class EnumOptions implements IEnumOptions { /** * Constructs a new EnumOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumOptions); /** EnumOptions allowAlias. */ public allowAlias: boolean; /** EnumOptions deprecated. */ public deprecated: boolean; /** EnumOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new EnumOptions instance using the specified properties. * @param [properties] Properties to set * @returns EnumOptions instance */ public static create(properties?: google.protobuf.IEnumOptions): google.protobuf.EnumOptions; /** * Encodes the specified EnumOptions message. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. * @param message EnumOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumOptions.verify|verify} messages. * @param message EnumOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumOptions; /** * Decodes an EnumOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumOptions; /** * Verifies an EnumOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumOptions; /** * Creates a plain object from an EnumOptions message. Also converts values to other types if specified. * @param message EnumOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an EnumValueOptions. */ interface IEnumValueOptions { /** EnumValueOptions deprecated */ deprecated?: (boolean|null); /** EnumValueOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); } /** Represents an EnumValueOptions. */ class EnumValueOptions implements IEnumValueOptions { /** * Constructs a new EnumValueOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEnumValueOptions); /** EnumValueOptions deprecated. */ public deprecated: boolean; /** EnumValueOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new EnumValueOptions instance using the specified properties. * @param [properties] Properties to set * @returns EnumValueOptions instance */ public static create(properties?: google.protobuf.IEnumValueOptions): google.protobuf.EnumValueOptions; /** * Encodes the specified EnumValueOptions message. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. * @param message EnumValueOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified EnumValueOptions message, length delimited. Does not implicitly {@link google.protobuf.EnumValueOptions.verify|verify} messages. * @param message EnumValueOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEnumValueOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an EnumValueOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns EnumValueOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.EnumValueOptions; /** * Decodes an EnumValueOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns EnumValueOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.EnumValueOptions; /** * Verifies an EnumValueOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an EnumValueOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns EnumValueOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.EnumValueOptions; /** * Creates a plain object from an EnumValueOptions message. Also converts values to other types if specified. * @param message EnumValueOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.EnumValueOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this EnumValueOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ServiceOptions. */ interface IServiceOptions { /** ServiceOptions deprecated */ deprecated?: (boolean|null); /** ServiceOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); /** ServiceOptions .google.api.defaultHost */ ".google.api.defaultHost"?: (string|null); /** ServiceOptions .google.api.oauthScopes */ ".google.api.oauthScopes"?: (string|null); } /** Represents a ServiceOptions. */ class ServiceOptions implements IServiceOptions { /** * Constructs a new ServiceOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IServiceOptions); /** ServiceOptions deprecated. */ public deprecated: boolean; /** ServiceOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new ServiceOptions instance using the specified properties. * @param [properties] Properties to set * @returns ServiceOptions instance */ public static create(properties?: google.protobuf.IServiceOptions): google.protobuf.ServiceOptions; /** * Encodes the specified ServiceOptions message. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. * @param message ServiceOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ServiceOptions message, length delimited. Does not implicitly {@link google.protobuf.ServiceOptions.verify|verify} messages. * @param message ServiceOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IServiceOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ServiceOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ServiceOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ServiceOptions; /** * Decodes a ServiceOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ServiceOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ServiceOptions; /** * Verifies a ServiceOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ServiceOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ServiceOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.ServiceOptions; /** * Creates a plain object from a ServiceOptions message. Also converts values to other types if specified. * @param message ServiceOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ServiceOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ServiceOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MethodOptions. */ interface IMethodOptions { /** MethodOptions deprecated */ deprecated?: (boolean|null); /** MethodOptions idempotencyLevel */ idempotencyLevel?: (google.protobuf.MethodOptions.IdempotencyLevel|keyof typeof google.protobuf.MethodOptions.IdempotencyLevel|null); /** MethodOptions uninterpretedOption */ uninterpretedOption?: (google.protobuf.IUninterpretedOption[]|null); /** MethodOptions .google.api.http */ ".google.api.http"?: (google.api.IHttpRule|null); /** MethodOptions .google.api.methodSignature */ ".google.api.methodSignature"?: (string[]|null); /** MethodOptions .google.longrunning.operationInfo */ ".google.longrunning.operationInfo"?: (google.longrunning.IOperationInfo|null); } /** Represents a MethodOptions. */ class MethodOptions implements IMethodOptions { /** * Constructs a new MethodOptions. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IMethodOptions); /** MethodOptions deprecated. */ public deprecated: boolean; /** MethodOptions idempotencyLevel. */ public idempotencyLevel: (google.protobuf.MethodOptions.IdempotencyLevel|keyof typeof google.protobuf.MethodOptions.IdempotencyLevel); /** MethodOptions uninterpretedOption. */ public uninterpretedOption: google.protobuf.IUninterpretedOption[]; /** * Creates a new MethodOptions instance using the specified properties. * @param [properties] Properties to set * @returns MethodOptions instance */ public static create(properties?: google.protobuf.IMethodOptions): google.protobuf.MethodOptions; /** * Encodes the specified MethodOptions message. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. * @param message MethodOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MethodOptions message, length delimited. Does not implicitly {@link google.protobuf.MethodOptions.verify|verify} messages. * @param message MethodOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IMethodOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MethodOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MethodOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.MethodOptions; /** * Decodes a MethodOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MethodOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.MethodOptions; /** * Verifies a MethodOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MethodOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MethodOptions */ public static fromObject(object: { [k: string]: any }): google.protobuf.MethodOptions; /** * Creates a plain object from a MethodOptions message. Also converts values to other types if specified. * @param message MethodOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.MethodOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MethodOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace MethodOptions { /** IdempotencyLevel enum. */ enum IdempotencyLevel { IDEMPOTENCY_UNKNOWN = 0, NO_SIDE_EFFECTS = 1, IDEMPOTENT = 2 } } /** Properties of an UninterpretedOption. */ interface IUninterpretedOption { /** UninterpretedOption name */ name?: (google.protobuf.UninterpretedOption.INamePart[]|null); /** UninterpretedOption identifierValue */ identifierValue?: (string|null); /** UninterpretedOption positiveIntValue */ positiveIntValue?: (number|Long|string|null); /** UninterpretedOption negativeIntValue */ negativeIntValue?: (number|Long|string|null); /** UninterpretedOption doubleValue */ doubleValue?: (number|null); /** UninterpretedOption stringValue */ stringValue?: (Uint8Array|string|null); /** UninterpretedOption aggregateValue */ aggregateValue?: (string|null); } /** Represents an UninterpretedOption. */ class UninterpretedOption implements IUninterpretedOption { /** * Constructs a new UninterpretedOption. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IUninterpretedOption); /** UninterpretedOption name. */ public name: google.protobuf.UninterpretedOption.INamePart[]; /** UninterpretedOption identifierValue. */ public identifierValue: string; /** UninterpretedOption positiveIntValue. */ public positiveIntValue: (number|Long|string); /** UninterpretedOption negativeIntValue. */ public negativeIntValue: (number|Long|string); /** UninterpretedOption doubleValue. */ public doubleValue: number; /** UninterpretedOption stringValue. */ public stringValue: (Uint8Array|string); /** UninterpretedOption aggregateValue. */ public aggregateValue: string; /** * Creates a new UninterpretedOption instance using the specified properties. * @param [properties] Properties to set * @returns UninterpretedOption instance */ public static create(properties?: google.protobuf.IUninterpretedOption): google.protobuf.UninterpretedOption; /** * Encodes the specified UninterpretedOption message. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. * @param message UninterpretedOption message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified UninterpretedOption message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.verify|verify} messages. * @param message UninterpretedOption message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IUninterpretedOption, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an UninterpretedOption message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns UninterpretedOption * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption; /** * Decodes an UninterpretedOption message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns UninterpretedOption * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption; /** * Verifies an UninterpretedOption message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an UninterpretedOption message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns UninterpretedOption */ public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption; /** * Creates a plain object from an UninterpretedOption message. Also converts values to other types if specified. * @param message UninterpretedOption * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.UninterpretedOption, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this UninterpretedOption to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace UninterpretedOption { /** Properties of a NamePart. */ interface INamePart { /** NamePart namePart */ namePart: string; /** NamePart isExtension */ isExtension: boolean; } /** Represents a NamePart. */ class NamePart implements INamePart { /** * Constructs a new NamePart. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.UninterpretedOption.INamePart); /** NamePart namePart. */ public namePart: string; /** NamePart isExtension. */ public isExtension: boolean; /** * Creates a new NamePart instance using the specified properties. * @param [properties] Properties to set * @returns NamePart instance */ public static create(properties?: google.protobuf.UninterpretedOption.INamePart): google.protobuf.UninterpretedOption.NamePart; /** * Encodes the specified NamePart message. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. * @param message NamePart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified NamePart message, length delimited. Does not implicitly {@link google.protobuf.UninterpretedOption.NamePart.verify|verify} messages. * @param message NamePart message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.UninterpretedOption.INamePart, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a NamePart message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns NamePart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.UninterpretedOption.NamePart; /** * Decodes a NamePart message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns NamePart * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.UninterpretedOption.NamePart; /** * Verifies a NamePart message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a NamePart message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns NamePart */ public static fromObject(object: { [k: string]: any }): google.protobuf.UninterpretedOption.NamePart; /** * Creates a plain object from a NamePart message. Also converts values to other types if specified. * @param message NamePart * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.UninterpretedOption.NamePart, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this NamePart to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a SourceCodeInfo. */ interface ISourceCodeInfo { /** SourceCodeInfo location */ location?: (google.protobuf.SourceCodeInfo.ILocation[]|null); } /** Represents a SourceCodeInfo. */ class SourceCodeInfo implements ISourceCodeInfo { /** * Constructs a new SourceCodeInfo. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.ISourceCodeInfo); /** SourceCodeInfo location. */ public location: google.protobuf.SourceCodeInfo.ILocation[]; /** * Creates a new SourceCodeInfo instance using the specified properties. * @param [properties] Properties to set * @returns SourceCodeInfo instance */ public static create(properties?: google.protobuf.ISourceCodeInfo): google.protobuf.SourceCodeInfo; /** * Encodes the specified SourceCodeInfo message. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. * @param message SourceCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified SourceCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.verify|verify} messages. * @param message SourceCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.ISourceCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SourceCodeInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns SourceCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo; /** * Decodes a SourceCodeInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns SourceCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo; /** * Verifies a SourceCodeInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a SourceCodeInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns SourceCodeInfo */ public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo; /** * Creates a plain object from a SourceCodeInfo message. Also converts values to other types if specified. * @param message SourceCodeInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.SourceCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SourceCodeInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace SourceCodeInfo { /** Properties of a Location. */ interface ILocation { /** Location path */ path?: (number[]|null); /** Location span */ span?: (number[]|null); /** Location leadingComments */ leadingComments?: (string|null); /** Location trailingComments */ trailingComments?: (string|null); /** Location leadingDetachedComments */ leadingDetachedComments?: (string[]|null); } /** Represents a Location. */ class Location implements ILocation { /** * Constructs a new Location. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.SourceCodeInfo.ILocation); /** Location path. */ public path: number[]; /** Location span. */ public span: number[]; /** Location leadingComments. */ public leadingComments: string; /** Location trailingComments. */ public trailingComments: string; /** Location leadingDetachedComments. */ public leadingDetachedComments: string[]; /** * Creates a new Location instance using the specified properties. * @param [properties] Properties to set * @returns Location instance */ public static create(properties?: google.protobuf.SourceCodeInfo.ILocation): google.protobuf.SourceCodeInfo.Location; /** * Encodes the specified Location message. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. * @param message Location message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Location message, length delimited. Does not implicitly {@link google.protobuf.SourceCodeInfo.Location.verify|verify} messages. * @param message Location message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.SourceCodeInfo.ILocation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Location message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Location * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.SourceCodeInfo.Location; /** * Decodes a Location message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Location * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.SourceCodeInfo.Location; /** * Verifies a Location message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Location message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Location */ public static fromObject(object: { [k: string]: any }): google.protobuf.SourceCodeInfo.Location; /** * Creates a plain object from a Location message. Also converts values to other types if specified. * @param message Location * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.SourceCodeInfo.Location, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Location to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a GeneratedCodeInfo. */ interface IGeneratedCodeInfo { /** GeneratedCodeInfo annotation */ annotation?: (google.protobuf.GeneratedCodeInfo.IAnnotation[]|null); } /** Represents a GeneratedCodeInfo. */ class GeneratedCodeInfo implements IGeneratedCodeInfo { /** * Constructs a new GeneratedCodeInfo. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IGeneratedCodeInfo); /** GeneratedCodeInfo annotation. */ public annotation: google.protobuf.GeneratedCodeInfo.IAnnotation[]; /** * Creates a new GeneratedCodeInfo instance using the specified properties. * @param [properties] Properties to set * @returns GeneratedCodeInfo instance */ public static create(properties?: google.protobuf.IGeneratedCodeInfo): google.protobuf.GeneratedCodeInfo; /** * Encodes the specified GeneratedCodeInfo message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. * @param message GeneratedCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GeneratedCodeInfo message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.verify|verify} messages. * @param message GeneratedCodeInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IGeneratedCodeInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GeneratedCodeInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GeneratedCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo; /** * Decodes a GeneratedCodeInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GeneratedCodeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo; /** * Verifies a GeneratedCodeInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GeneratedCodeInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GeneratedCodeInfo */ public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo; /** * Creates a plain object from a GeneratedCodeInfo message. Also converts values to other types if specified. * @param message GeneratedCodeInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.GeneratedCodeInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GeneratedCodeInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace GeneratedCodeInfo { /** Properties of an Annotation. */ interface IAnnotation { /** Annotation path */ path?: (number[]|null); /** Annotation sourceFile */ sourceFile?: (string|null); /** Annotation begin */ begin?: (number|null); /** Annotation end */ end?: (number|null); } /** Represents an Annotation. */ class Annotation implements IAnnotation { /** * Constructs a new Annotation. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation); /** Annotation path. */ public path: number[]; /** Annotation sourceFile. */ public sourceFile: string; /** Annotation begin. */ public begin: number; /** Annotation end. */ public end: number; /** * Creates a new Annotation instance using the specified properties. * @param [properties] Properties to set * @returns Annotation instance */ public static create(properties?: google.protobuf.GeneratedCodeInfo.IAnnotation): google.protobuf.GeneratedCodeInfo.Annotation; /** * Encodes the specified Annotation message. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. * @param message Annotation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Annotation message, length delimited. Does not implicitly {@link google.protobuf.GeneratedCodeInfo.Annotation.verify|verify} messages. * @param message Annotation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.GeneratedCodeInfo.IAnnotation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Annotation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Annotation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.GeneratedCodeInfo.Annotation; /** * Decodes an Annotation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Annotation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.GeneratedCodeInfo.Annotation; /** * Verifies an Annotation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Annotation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Annotation */ public static fromObject(object: { [k: string]: any }): google.protobuf.GeneratedCodeInfo.Annotation; /** * Creates a plain object from an Annotation message. Also converts values to other types if specified. * @param message Annotation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.GeneratedCodeInfo.Annotation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Annotation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of an Any. */ interface IAny { /** Any type_url */ type_url?: (string|null); /** Any value */ value?: (Uint8Array|string|null); } /** Represents an Any. */ class Any implements IAny { /** * Constructs a new Any. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IAny); /** Any type_url. */ public type_url: string; /** Any value. */ public value: (Uint8Array|string); /** * Creates a new Any instance using the specified properties. * @param [properties] Properties to set * @returns Any instance */ public static create(properties?: google.protobuf.IAny): google.protobuf.Any; /** * Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. * @param message Any message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. * @param message Any message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Any message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Any * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any; /** * Decodes an Any message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Any * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any; /** * Verifies an Any message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Any message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Any */ public static fromObject(object: { [k: string]: any }): google.protobuf.Any; /** * Creates a plain object from an Any message. Also converts values to other types if specified. * @param message Any * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Any to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Empty. */ interface IEmpty { } /** Represents an Empty. */ class Empty implements IEmpty { /** * Constructs a new Empty. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IEmpty); /** * Creates a new Empty instance using the specified properties. * @param [properties] Properties to set * @returns Empty instance */ public static create(properties?: google.protobuf.IEmpty): google.protobuf.Empty; /** * Encodes the specified Empty message. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. * @param message Empty message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Empty message, length delimited. Does not implicitly {@link google.protobuf.Empty.verify|verify} messages. * @param message Empty message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IEmpty, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Empty message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Empty * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Empty; /** * Decodes an Empty message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Empty * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Empty; /** * Verifies an Empty message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Empty message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Empty */ public static fromObject(object: { [k: string]: any }): google.protobuf.Empty; /** * Creates a plain object from an Empty message. Also converts values to other types if specified. * @param message Empty * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Empty, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Empty to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Timestamp. */ interface ITimestamp { /** Timestamp seconds */ seconds?: (number|Long|string|null); /** Timestamp nanos */ nanos?: (number|null); } /** Represents a Timestamp. */ class Timestamp implements ITimestamp { /** * Constructs a new Timestamp. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.ITimestamp); /** Timestamp seconds. */ public seconds: (number|Long|string); /** Timestamp nanos. */ public nanos: number; /** * Creates a new Timestamp instance using the specified properties. * @param [properties] Properties to set * @returns Timestamp instance */ public static create(properties?: google.protobuf.ITimestamp): google.protobuf.Timestamp; /** * Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. * @param message Timestamp message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Timestamp message, length delimited. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. * @param message Timestamp message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.ITimestamp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Timestamp message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Timestamp * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Timestamp; /** * Decodes a Timestamp message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Timestamp * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Timestamp; /** * Verifies a Timestamp message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Timestamp */ public static fromObject(object: { [k: string]: any }): google.protobuf.Timestamp; /** * Creates a plain object from a Timestamp message. Also converts values to other types if specified. * @param message Timestamp * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Timestamp, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Timestamp to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a FieldMask. */ interface IFieldMask { /** FieldMask paths */ paths?: (string[]|null); } /** Represents a FieldMask. */ class FieldMask implements IFieldMask { /** * Constructs a new FieldMask. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IFieldMask); /** FieldMask paths. */ public paths: string[]; /** * Creates a new FieldMask instance using the specified properties. * @param [properties] Properties to set * @returns FieldMask instance */ public static create(properties?: google.protobuf.IFieldMask): google.protobuf.FieldMask; /** * Encodes the specified FieldMask message. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. * @param message FieldMask message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IFieldMask, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FieldMask message, length delimited. Does not implicitly {@link google.protobuf.FieldMask.verify|verify} messages. * @param message FieldMask message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IFieldMask, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FieldMask message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FieldMask * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.FieldMask; /** * Decodes a FieldMask message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FieldMask * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.FieldMask; /** * Verifies a FieldMask message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FieldMask message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FieldMask */ public static fromObject(object: { [k: string]: any }): google.protobuf.FieldMask; /** * Creates a plain object from a FieldMask message. Also converts values to other types if specified. * @param message FieldMask * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.FieldMask, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FieldMask to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Struct. */ interface IStruct { /** Struct fields */ fields?: ({ [k: string]: google.protobuf.IValue }|null); } /** Represents a Struct. */ class Struct implements IStruct { /** * Constructs a new Struct. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IStruct); /** Struct fields. */ public fields: { [k: string]: google.protobuf.IValue }; /** * Creates a new Struct instance using the specified properties. * @param [properties] Properties to set * @returns Struct instance */ public static create(properties?: google.protobuf.IStruct): google.protobuf.Struct; /** * Encodes the specified Struct message. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. * @param message Struct message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IStruct, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Struct message, length delimited. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages. * @param message Struct message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IStruct, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Struct message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Struct * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Struct; /** * Decodes a Struct message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Struct * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Struct; /** * Verifies a Struct message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Struct message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Struct */ public static fromObject(object: { [k: string]: any }): google.protobuf.Struct; /** * Creates a plain object from a Struct message. Also converts values to other types if specified. * @param message Struct * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Struct to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Value. */ interface IValue { /** Value nullValue */ nullValue?: (google.protobuf.NullValue|keyof typeof google.protobuf.NullValue|null); /** Value numberValue */ numberValue?: (number|null); /** Value stringValue */ stringValue?: (string|null); /** Value boolValue */ boolValue?: (boolean|null); /** Value structValue */ structValue?: (google.protobuf.IStruct|null); /** Value listValue */ listValue?: (google.protobuf.IListValue|null); } /** Represents a Value. */ class Value implements IValue { /** * Constructs a new Value. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IValue); /** Value nullValue. */ public nullValue: (google.protobuf.NullValue|keyof typeof google.protobuf.NullValue); /** Value numberValue. */ public numberValue: number; /** Value stringValue. */ public stringValue: string; /** Value boolValue. */ public boolValue: boolean; /** Value structValue. */ public structValue?: (google.protobuf.IStruct|null); /** Value listValue. */ public listValue?: (google.protobuf.IListValue|null); /** Value kind. */ public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue"); /** * Creates a new Value instance using the specified properties. * @param [properties] Properties to set * @returns Value instance */ public static create(properties?: google.protobuf.IValue): google.protobuf.Value; /** * Encodes the specified Value message. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. * @param message Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Value message, length delimited. Does not implicitly {@link google.protobuf.Value.verify|verify} messages. * @param message Value message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Value message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Value; /** * Decodes a Value message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Value * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Value; /** * Verifies a Value message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Value message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Value */ public static fromObject(object: { [k: string]: any }): google.protobuf.Value; /** * Creates a plain object from a Value message. Also converts values to other types if specified. * @param message Value * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Value to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** NullValue enum. */ enum NullValue { NULL_VALUE = 0 } /** Properties of a ListValue. */ interface IListValue { /** ListValue values */ values?: (google.protobuf.IValue[]|null); } /** Represents a ListValue. */ class ListValue implements IListValue { /** * Constructs a new ListValue. * @param [properties] Properties to set */ constructor(properties?: google.protobuf.IListValue); /** ListValue values. */ public values: google.protobuf.IValue[]; /** * Creates a new ListValue instance using the specified properties. * @param [properties] Properties to set * @returns ListValue instance */ public static create(properties?: google.protobuf.IListValue): google.protobuf.ListValue; /** * Encodes the specified ListValue message. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. * @param message ListValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.protobuf.IListValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListValue message, length delimited. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages. * @param message ListValue message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.protobuf.IListValue, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListValue message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ListValue; /** * Decodes a ListValue message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListValue * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ListValue; /** * Verifies a ListValue message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListValue message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListValue */ public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue; /** * Creates a plain object from a ListValue message. Also converts values to other types if specified. * @param message ListValue * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListValue to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Namespace rpc. */ namespace rpc { /** Properties of a RetryInfo. */ interface IRetryInfo { /** RetryInfo retryDelay */ retryDelay?: (google.protobuf.IDuration|null); } /** Represents a RetryInfo. */ class RetryInfo implements IRetryInfo { /** * Constructs a new RetryInfo. * @param [properties] Properties to set */ constructor(properties?: google.rpc.IRetryInfo); /** RetryInfo retryDelay. */ public retryDelay?: (google.protobuf.IDuration|null); /** * Creates a new RetryInfo instance using the specified properties. * @param [properties] Properties to set * @returns RetryInfo instance */ public static create(properties?: google.rpc.IRetryInfo): google.rpc.RetryInfo; /** * Encodes the specified RetryInfo message. Does not implicitly {@link google.rpc.RetryInfo.verify|verify} messages. * @param message RetryInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.IRetryInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified RetryInfo message, length delimited. Does not implicitly {@link google.rpc.RetryInfo.verify|verify} messages. * @param message RetryInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.IRetryInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a RetryInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns RetryInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.RetryInfo; /** * Decodes a RetryInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns RetryInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.RetryInfo; /** * Verifies a RetryInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a RetryInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns RetryInfo */ public static fromObject(object: { [k: string]: any }): google.rpc.RetryInfo; /** * Creates a plain object from a RetryInfo message. Also converts values to other types if specified. * @param message RetryInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.RetryInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this RetryInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DebugInfo. */ interface IDebugInfo { /** DebugInfo stackEntries */ stackEntries?: (string[]|null); /** DebugInfo detail */ detail?: (string|null); } /** Represents a DebugInfo. */ class DebugInfo implements IDebugInfo { /** * Constructs a new DebugInfo. * @param [properties] Properties to set */ constructor(properties?: google.rpc.IDebugInfo); /** DebugInfo stackEntries. */ public stackEntries: string[]; /** DebugInfo detail. */ public detail: string; /** * Creates a new DebugInfo instance using the specified properties. * @param [properties] Properties to set * @returns DebugInfo instance */ public static create(properties?: google.rpc.IDebugInfo): google.rpc.DebugInfo; /** * Encodes the specified DebugInfo message. Does not implicitly {@link google.rpc.DebugInfo.verify|verify} messages. * @param message DebugInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.IDebugInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DebugInfo message, length delimited. Does not implicitly {@link google.rpc.DebugInfo.verify|verify} messages. * @param message DebugInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.IDebugInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DebugInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DebugInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.DebugInfo; /** * Decodes a DebugInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DebugInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.DebugInfo; /** * Verifies a DebugInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DebugInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DebugInfo */ public static fromObject(object: { [k: string]: any }): google.rpc.DebugInfo; /** * Creates a plain object from a DebugInfo message. Also converts values to other types if specified. * @param message DebugInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.DebugInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DebugInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a QuotaFailure. */ interface IQuotaFailure { /** QuotaFailure violations */ violations?: (google.rpc.QuotaFailure.IViolation[]|null); } /** Represents a QuotaFailure. */ class QuotaFailure implements IQuotaFailure { /** * Constructs a new QuotaFailure. * @param [properties] Properties to set */ constructor(properties?: google.rpc.IQuotaFailure); /** QuotaFailure violations. */ public violations: google.rpc.QuotaFailure.IViolation[]; /** * Creates a new QuotaFailure instance using the specified properties. * @param [properties] Properties to set * @returns QuotaFailure instance */ public static create(properties?: google.rpc.IQuotaFailure): google.rpc.QuotaFailure; /** * Encodes the specified QuotaFailure message. Does not implicitly {@link google.rpc.QuotaFailure.verify|verify} messages. * @param message QuotaFailure message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.IQuotaFailure, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified QuotaFailure message, length delimited. Does not implicitly {@link google.rpc.QuotaFailure.verify|verify} messages. * @param message QuotaFailure message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.IQuotaFailure, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a QuotaFailure message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns QuotaFailure * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.QuotaFailure; /** * Decodes a QuotaFailure message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns QuotaFailure * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.QuotaFailure; /** * Verifies a QuotaFailure message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a QuotaFailure message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns QuotaFailure */ public static fromObject(object: { [k: string]: any }): google.rpc.QuotaFailure; /** * Creates a plain object from a QuotaFailure message. Also converts values to other types if specified. * @param message QuotaFailure * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.QuotaFailure, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this QuotaFailure to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace QuotaFailure { /** Properties of a Violation. */ interface IViolation { /** Violation subject */ subject?: (string|null); /** Violation description */ description?: (string|null); } /** Represents a Violation. */ class Violation implements IViolation { /** * Constructs a new Violation. * @param [properties] Properties to set */ constructor(properties?: google.rpc.QuotaFailure.IViolation); /** Violation subject. */ public subject: string; /** Violation description. */ public description: string; /** * Creates a new Violation instance using the specified properties. * @param [properties] Properties to set * @returns Violation instance */ public static create(properties?: google.rpc.QuotaFailure.IViolation): google.rpc.QuotaFailure.Violation; /** * Encodes the specified Violation message. Does not implicitly {@link google.rpc.QuotaFailure.Violation.verify|verify} messages. * @param message Violation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.QuotaFailure.IViolation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Violation message, length delimited. Does not implicitly {@link google.rpc.QuotaFailure.Violation.verify|verify} messages. * @param message Violation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.QuotaFailure.IViolation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Violation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Violation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.QuotaFailure.Violation; /** * Decodes a Violation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Violation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.QuotaFailure.Violation; /** * Verifies a Violation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Violation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Violation */ public static fromObject(object: { [k: string]: any }): google.rpc.QuotaFailure.Violation; /** * Creates a plain object from a Violation message. Also converts values to other types if specified. * @param message Violation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.QuotaFailure.Violation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Violation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a BadRequest. */ interface IBadRequest { /** BadRequest fieldViolations */ fieldViolations?: (google.rpc.BadRequest.IFieldViolation[]|null); } /** Represents a BadRequest. */ class BadRequest implements IBadRequest { /** * Constructs a new BadRequest. * @param [properties] Properties to set */ constructor(properties?: google.rpc.IBadRequest); /** BadRequest fieldViolations. */ public fieldViolations: google.rpc.BadRequest.IFieldViolation[]; /** * Creates a new BadRequest instance using the specified properties. * @param [properties] Properties to set * @returns BadRequest instance */ public static create(properties?: google.rpc.IBadRequest): google.rpc.BadRequest; /** * Encodes the specified BadRequest message. Does not implicitly {@link google.rpc.BadRequest.verify|verify} messages. * @param message BadRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.IBadRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BadRequest message, length delimited. Does not implicitly {@link google.rpc.BadRequest.verify|verify} messages. * @param message BadRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.IBadRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BadRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BadRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.BadRequest; /** * Decodes a BadRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BadRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.BadRequest; /** * Verifies a BadRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BadRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BadRequest */ public static fromObject(object: { [k: string]: any }): google.rpc.BadRequest; /** * Creates a plain object from a BadRequest message. Also converts values to other types if specified. * @param message BadRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.BadRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BadRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace BadRequest { /** Properties of a FieldViolation. */ interface IFieldViolation { /** FieldViolation field */ field?: (string|null); /** FieldViolation description */ description?: (string|null); } /** Represents a FieldViolation. */ class FieldViolation implements IFieldViolation { /** * Constructs a new FieldViolation. * @param [properties] Properties to set */ constructor(properties?: google.rpc.BadRequest.IFieldViolation); /** FieldViolation field. */ public field: string; /** FieldViolation description. */ public description: string; /** * Creates a new FieldViolation instance using the specified properties. * @param [properties] Properties to set * @returns FieldViolation instance */ public static create(properties?: google.rpc.BadRequest.IFieldViolation): google.rpc.BadRequest.FieldViolation; /** * Encodes the specified FieldViolation message. Does not implicitly {@link google.rpc.BadRequest.FieldViolation.verify|verify} messages. * @param message FieldViolation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.BadRequest.IFieldViolation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified FieldViolation message, length delimited. Does not implicitly {@link google.rpc.BadRequest.FieldViolation.verify|verify} messages. * @param message FieldViolation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.BadRequest.IFieldViolation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a FieldViolation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns FieldViolation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.BadRequest.FieldViolation; /** * Decodes a FieldViolation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns FieldViolation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.BadRequest.FieldViolation; /** * Verifies a FieldViolation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a FieldViolation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns FieldViolation */ public static fromObject(object: { [k: string]: any }): google.rpc.BadRequest.FieldViolation; /** * Creates a plain object from a FieldViolation message. Also converts values to other types if specified. * @param message FieldViolation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.BadRequest.FieldViolation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this FieldViolation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a RequestInfo. */ interface IRequestInfo { /** RequestInfo requestId */ requestId?: (string|null); /** RequestInfo servingData */ servingData?: (string|null); } /** Represents a RequestInfo. */ class RequestInfo implements IRequestInfo { /** * Constructs a new RequestInfo. * @param [properties] Properties to set */ constructor(properties?: google.rpc.IRequestInfo); /** RequestInfo requestId. */ public requestId: string; /** RequestInfo servingData. */ public servingData: string; /** * Creates a new RequestInfo instance using the specified properties. * @param [properties] Properties to set * @returns RequestInfo instance */ public static create(properties?: google.rpc.IRequestInfo): google.rpc.RequestInfo; /** * Encodes the specified RequestInfo message. Does not implicitly {@link google.rpc.RequestInfo.verify|verify} messages. * @param message RequestInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.IRequestInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified RequestInfo message, length delimited. Does not implicitly {@link google.rpc.RequestInfo.verify|verify} messages. * @param message RequestInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.IRequestInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a RequestInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns RequestInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.RequestInfo; /** * Decodes a RequestInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns RequestInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.RequestInfo; /** * Verifies a RequestInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a RequestInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns RequestInfo */ public static fromObject(object: { [k: string]: any }): google.rpc.RequestInfo; /** * Creates a plain object from a RequestInfo message. Also converts values to other types if specified. * @param message RequestInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.RequestInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this RequestInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ResourceInfo. */ interface IResourceInfo { /** ResourceInfo resourceType */ resourceType?: (string|null); /** ResourceInfo resourceName */ resourceName?: (string|null); /** ResourceInfo owner */ owner?: (string|null); /** ResourceInfo description */ description?: (string|null); } /** Represents a ResourceInfo. */ class ResourceInfo implements IResourceInfo { /** * Constructs a new ResourceInfo. * @param [properties] Properties to set */ constructor(properties?: google.rpc.IResourceInfo); /** ResourceInfo resourceType. */ public resourceType: string; /** ResourceInfo resourceName. */ public resourceName: string; /** ResourceInfo owner. */ public owner: string; /** ResourceInfo description. */ public description: string; /** * Creates a new ResourceInfo instance using the specified properties. * @param [properties] Properties to set * @returns ResourceInfo instance */ public static create(properties?: google.rpc.IResourceInfo): google.rpc.ResourceInfo; /** * Encodes the specified ResourceInfo message. Does not implicitly {@link google.rpc.ResourceInfo.verify|verify} messages. * @param message ResourceInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.IResourceInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ResourceInfo message, length delimited. Does not implicitly {@link google.rpc.ResourceInfo.verify|verify} messages. * @param message ResourceInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.IResourceInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ResourceInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ResourceInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.ResourceInfo; /** * Decodes a ResourceInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ResourceInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.ResourceInfo; /** * Verifies a ResourceInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ResourceInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ResourceInfo */ public static fromObject(object: { [k: string]: any }): google.rpc.ResourceInfo; /** * Creates a plain object from a ResourceInfo message. Also converts values to other types if specified. * @param message ResourceInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.ResourceInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ResourceInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Help. */ interface IHelp { /** Help links */ links?: (google.rpc.Help.ILink[]|null); } /** Represents a Help. */ class Help implements IHelp { /** * Constructs a new Help. * @param [properties] Properties to set */ constructor(properties?: google.rpc.IHelp); /** Help links. */ public links: google.rpc.Help.ILink[]; /** * Creates a new Help instance using the specified properties. * @param [properties] Properties to set * @returns Help instance */ public static create(properties?: google.rpc.IHelp): google.rpc.Help; /** * Encodes the specified Help message. Does not implicitly {@link google.rpc.Help.verify|verify} messages. * @param message Help message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.IHelp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Help message, length delimited. Does not implicitly {@link google.rpc.Help.verify|verify} messages. * @param message Help message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.IHelp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Help message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Help * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Help; /** * Decodes a Help message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Help * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Help; /** * Verifies a Help message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Help message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Help */ public static fromObject(object: { [k: string]: any }): google.rpc.Help; /** * Creates a plain object from a Help message. Also converts values to other types if specified. * @param message Help * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.Help, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Help to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Help { /** Properties of a Link. */ interface ILink { /** Link description */ description?: (string|null); /** Link url */ url?: (string|null); } /** Represents a Link. */ class Link implements ILink { /** * Constructs a new Link. * @param [properties] Properties to set */ constructor(properties?: google.rpc.Help.ILink); /** Link description. */ public description: string; /** Link url. */ public url: string; /** * Creates a new Link instance using the specified properties. * @param [properties] Properties to set * @returns Link instance */ public static create(properties?: google.rpc.Help.ILink): google.rpc.Help.Link; /** * Encodes the specified Link message. Does not implicitly {@link google.rpc.Help.Link.verify|verify} messages. * @param message Link message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.Help.ILink, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Link message, length delimited. Does not implicitly {@link google.rpc.Help.Link.verify|verify} messages. * @param message Link message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.Help.ILink, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Link message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Link * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Help.Link; /** * Decodes a Link message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Link * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Help.Link; /** * Verifies a Link message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Link message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Link */ public static fromObject(object: { [k: string]: any }): google.rpc.Help.Link; /** * Creates a plain object from a Link message. Also converts values to other types if specified. * @param message Link * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.Help.Link, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Link to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a LocalizedMessage. */ interface ILocalizedMessage { /** LocalizedMessage locale */ locale?: (string|null); /** LocalizedMessage message */ message?: (string|null); } /** Represents a LocalizedMessage. */ class LocalizedMessage implements ILocalizedMessage { /** * Constructs a new LocalizedMessage. * @param [properties] Properties to set */ constructor(properties?: google.rpc.ILocalizedMessage); /** LocalizedMessage locale. */ public locale: string; /** LocalizedMessage message. */ public message: string; /** * Creates a new LocalizedMessage instance using the specified properties. * @param [properties] Properties to set * @returns LocalizedMessage instance */ public static create(properties?: google.rpc.ILocalizedMessage): google.rpc.LocalizedMessage; /** * Encodes the specified LocalizedMessage message. Does not implicitly {@link google.rpc.LocalizedMessage.verify|verify} messages. * @param message LocalizedMessage message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.ILocalizedMessage, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified LocalizedMessage message, length delimited. Does not implicitly {@link google.rpc.LocalizedMessage.verify|verify} messages. * @param message LocalizedMessage message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.ILocalizedMessage, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a LocalizedMessage message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns LocalizedMessage * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.LocalizedMessage; /** * Decodes a LocalizedMessage message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns LocalizedMessage * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.LocalizedMessage; /** * Verifies a LocalizedMessage message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a LocalizedMessage message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns LocalizedMessage */ public static fromObject(object: { [k: string]: any }): google.rpc.LocalizedMessage; /** * Creates a plain object from a LocalizedMessage message. Also converts values to other types if specified. * @param message LocalizedMessage * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.LocalizedMessage, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this LocalizedMessage to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Status. */ interface IStatus { /** Status code */ code?: (number|null); /** Status message */ message?: (string|null); /** Status details */ details?: (google.protobuf.IAny[]|null); } /** Represents a Status. */ class Status implements IStatus { /** * Constructs a new Status. * @param [properties] Properties to set */ constructor(properties?: google.rpc.IStatus); /** Status code. */ public code: number; /** Status message. */ public message: string; /** Status details. */ public details: google.protobuf.IAny[]; /** * Creates a new Status instance using the specified properties. * @param [properties] Properties to set * @returns Status instance */ public static create(properties?: google.rpc.IStatus): google.rpc.Status; /** * Encodes the specified Status message. Does not implicitly {@link google.rpc.Status.verify|verify} messages. * @param message Status message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Status message, length delimited. Does not implicitly {@link google.rpc.Status.verify|verify} messages. * @param message Status message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Status message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Status * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Status; /** * Decodes a Status message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Status * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Status; /** * Verifies a Status message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Status message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Status */ public static fromObject(object: { [k: string]: any }): google.rpc.Status; /** * Creates a plain object from a Status message. Also converts values to other types if specified. * @param message Status * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Status to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Namespace spanner. */ namespace spanner { /** Namespace admin. */ namespace admin { /** Namespace database. */ namespace database { /** Namespace v1. */ namespace v1 { /** Represents a DatabaseAdmin */ class DatabaseAdmin extends $protobuf.rpc.Service { /** * Constructs a new DatabaseAdmin service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new DatabaseAdmin service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): DatabaseAdmin; /** * Calls ListDatabases. * @param request ListDatabasesRequest message or plain object * @param callback Node-style callback called with the error, if any, and ListDatabasesResponse */ public listDatabases(request: google.spanner.admin.database.v1.IListDatabasesRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.ListDatabasesCallback): void; /** * Calls ListDatabases. * @param request ListDatabasesRequest message or plain object * @returns Promise */ public listDatabases(request: google.spanner.admin.database.v1.IListDatabasesRequest): Promise<google.spanner.admin.database.v1.ListDatabasesResponse>; /** * Calls CreateDatabase. * @param request CreateDatabaseRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public createDatabase(request: google.spanner.admin.database.v1.ICreateDatabaseRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabaseCallback): void; /** * Calls CreateDatabase. * @param request CreateDatabaseRequest message or plain object * @returns Promise */ public createDatabase(request: google.spanner.admin.database.v1.ICreateDatabaseRequest): Promise<google.longrunning.Operation>; /** * Calls GetDatabase. * @param request GetDatabaseRequest message or plain object * @param callback Node-style callback called with the error, if any, and Database */ public getDatabase(request: google.spanner.admin.database.v1.IGetDatabaseRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseCallback): void; /** * Calls GetDatabase. * @param request GetDatabaseRequest message or plain object * @returns Promise */ public getDatabase(request: google.spanner.admin.database.v1.IGetDatabaseRequest): Promise<google.spanner.admin.database.v1.Database>; /** * Calls UpdateDatabaseDdl. * @param request UpdateDatabaseDdlRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public updateDatabaseDdl(request: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdlCallback): void; /** * Calls UpdateDatabaseDdl. * @param request UpdateDatabaseDdlRequest message or plain object * @returns Promise */ public updateDatabaseDdl(request: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest): Promise<google.longrunning.Operation>; /** * Calls DropDatabase. * @param request DropDatabaseRequest message or plain object * @param callback Node-style callback called with the error, if any, and Empty */ public dropDatabase(request: google.spanner.admin.database.v1.IDropDatabaseRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.DropDatabaseCallback): void; /** * Calls DropDatabase. * @param request DropDatabaseRequest message or plain object * @returns Promise */ public dropDatabase(request: google.spanner.admin.database.v1.IDropDatabaseRequest): Promise<google.protobuf.Empty>; /** * Calls GetDatabaseDdl. * @param request GetDatabaseDdlRequest message or plain object * @param callback Node-style callback called with the error, if any, and GetDatabaseDdlResponse */ public getDatabaseDdl(request: google.spanner.admin.database.v1.IGetDatabaseDdlRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdlCallback): void; /** * Calls GetDatabaseDdl. * @param request GetDatabaseDdlRequest message or plain object * @returns Promise */ public getDatabaseDdl(request: google.spanner.admin.database.v1.IGetDatabaseDdlRequest): Promise<google.spanner.admin.database.v1.GetDatabaseDdlResponse>; /** * Calls SetIamPolicy. * @param request SetIamPolicyRequest message or plain object * @param callback Node-style callback called with the error, if any, and Policy */ public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.SetIamPolicyCallback): void; /** * Calls SetIamPolicy. * @param request SetIamPolicyRequest message or plain object * @returns Promise */ public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest): Promise<google.iam.v1.Policy>; /** * Calls GetIamPolicy. * @param request GetIamPolicyRequest message or plain object * @param callback Node-style callback called with the error, if any, and Policy */ public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.GetIamPolicyCallback): void; /** * Calls GetIamPolicy. * @param request GetIamPolicyRequest message or plain object * @returns Promise */ public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest): Promise<google.iam.v1.Policy>; /** * Calls TestIamPermissions. * @param request TestIamPermissionsRequest message or plain object * @param callback Node-style callback called with the error, if any, and TestIamPermissionsResponse */ public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.TestIamPermissionsCallback): void; /** * Calls TestIamPermissions. * @param request TestIamPermissionsRequest message or plain object * @returns Promise */ public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest): Promise<google.iam.v1.TestIamPermissionsResponse>; /** * Calls CreateBackup. * @param request CreateBackupRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public createBackup(request: google.spanner.admin.database.v1.ICreateBackupRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.CreateBackupCallback): void; /** * Calls CreateBackup. * @param request CreateBackupRequest message or plain object * @returns Promise */ public createBackup(request: google.spanner.admin.database.v1.ICreateBackupRequest): Promise<google.longrunning.Operation>; /** * Calls GetBackup. * @param request GetBackupRequest message or plain object * @param callback Node-style callback called with the error, if any, and Backup */ public getBackup(request: google.spanner.admin.database.v1.IGetBackupRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.GetBackupCallback): void; /** * Calls GetBackup. * @param request GetBackupRequest message or plain object * @returns Promise */ public getBackup(request: google.spanner.admin.database.v1.IGetBackupRequest): Promise<google.spanner.admin.database.v1.Backup>; /** * Calls UpdateBackup. * @param request UpdateBackupRequest message or plain object * @param callback Node-style callback called with the error, if any, and Backup */ public updateBackup(request: google.spanner.admin.database.v1.IUpdateBackupRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.UpdateBackupCallback): void; /** * Calls UpdateBackup. * @param request UpdateBackupRequest message or plain object * @returns Promise */ public updateBackup(request: google.spanner.admin.database.v1.IUpdateBackupRequest): Promise<google.spanner.admin.database.v1.Backup>; /** * Calls DeleteBackup. * @param request DeleteBackupRequest message or plain object * @param callback Node-style callback called with the error, if any, and Empty */ public deleteBackup(request: google.spanner.admin.database.v1.IDeleteBackupRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.DeleteBackupCallback): void; /** * Calls DeleteBackup. * @param request DeleteBackupRequest message or plain object * @returns Promise */ public deleteBackup(request: google.spanner.admin.database.v1.IDeleteBackupRequest): Promise<google.protobuf.Empty>; /** * Calls ListBackups. * @param request ListBackupsRequest message or plain object * @param callback Node-style callback called with the error, if any, and ListBackupsResponse */ public listBackups(request: google.spanner.admin.database.v1.IListBackupsRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.ListBackupsCallback): void; /** * Calls ListBackups. * @param request ListBackupsRequest message or plain object * @returns Promise */ public listBackups(request: google.spanner.admin.database.v1.IListBackupsRequest): Promise<google.spanner.admin.database.v1.ListBackupsResponse>; /** * Calls RestoreDatabase. * @param request RestoreDatabaseRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public restoreDatabase(request: google.spanner.admin.database.v1.IRestoreDatabaseRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.RestoreDatabaseCallback): void; /** * Calls RestoreDatabase. * @param request RestoreDatabaseRequest message or plain object * @returns Promise */ public restoreDatabase(request: google.spanner.admin.database.v1.IRestoreDatabaseRequest): Promise<google.longrunning.Operation>; /** * Calls ListDatabaseOperations. * @param request ListDatabaseOperationsRequest message or plain object * @param callback Node-style callback called with the error, if any, and ListDatabaseOperationsResponse */ public listDatabaseOperations(request: google.spanner.admin.database.v1.IListDatabaseOperationsRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.ListDatabaseOperationsCallback): void; /** * Calls ListDatabaseOperations. * @param request ListDatabaseOperationsRequest message or plain object * @returns Promise */ public listDatabaseOperations(request: google.spanner.admin.database.v1.IListDatabaseOperationsRequest): Promise<google.spanner.admin.database.v1.ListDatabaseOperationsResponse>; /** * Calls ListBackupOperations. * @param request ListBackupOperationsRequest message or plain object * @param callback Node-style callback called with the error, if any, and ListBackupOperationsResponse */ public listBackupOperations(request: google.spanner.admin.database.v1.IListBackupOperationsRequest, callback: google.spanner.admin.database.v1.DatabaseAdmin.ListBackupOperationsCallback): void; /** * Calls ListBackupOperations. * @param request ListBackupOperationsRequest message or plain object * @returns Promise */ public listBackupOperations(request: google.spanner.admin.database.v1.IListBackupOperationsRequest): Promise<google.spanner.admin.database.v1.ListBackupOperationsResponse>; } namespace DatabaseAdmin { /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#listDatabases}. * @param error Error, if any * @param [response] ListDatabasesResponse */ type ListDatabasesCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.ListDatabasesResponse) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#createDatabase}. * @param error Error, if any * @param [response] Operation */ type CreateDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#getDatabase}. * @param error Error, if any * @param [response] Database */ type GetDatabaseCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.Database) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#updateDatabaseDdl}. * @param error Error, if any * @param [response] Operation */ type UpdateDatabaseDdlCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#dropDatabase}. * @param error Error, if any * @param [response] Empty */ type DropDatabaseCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#getDatabaseDdl}. * @param error Error, if any * @param [response] GetDatabaseDdlResponse */ type GetDatabaseDdlCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.GetDatabaseDdlResponse) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#setIamPolicy}. * @param error Error, if any * @param [response] Policy */ type SetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#getIamPolicy}. * @param error Error, if any * @param [response] Policy */ type GetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#testIamPermissions}. * @param error Error, if any * @param [response] TestIamPermissionsResponse */ type TestIamPermissionsCallback = (error: (Error|null), response?: google.iam.v1.TestIamPermissionsResponse) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#createBackup}. * @param error Error, if any * @param [response] Operation */ type CreateBackupCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#getBackup}. * @param error Error, if any * @param [response] Backup */ type GetBackupCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.Backup) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#updateBackup}. * @param error Error, if any * @param [response] Backup */ type UpdateBackupCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.Backup) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#deleteBackup}. * @param error Error, if any * @param [response] Empty */ type DeleteBackupCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#listBackups}. * @param error Error, if any * @param [response] ListBackupsResponse */ type ListBackupsCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.ListBackupsResponse) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#restoreDatabase}. * @param error Error, if any * @param [response] Operation */ type RestoreDatabaseCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#listDatabaseOperations}. * @param error Error, if any * @param [response] ListDatabaseOperationsResponse */ type ListDatabaseOperationsCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.ListDatabaseOperationsResponse) => void; /** * Callback as used by {@link google.spanner.admin.database.v1.DatabaseAdmin#listBackupOperations}. * @param error Error, if any * @param [response] ListBackupOperationsResponse */ type ListBackupOperationsCallback = (error: (Error|null), response?: google.spanner.admin.database.v1.ListBackupOperationsResponse) => void; } /** Properties of a RestoreInfo. */ interface IRestoreInfo { /** RestoreInfo sourceType */ sourceType?: (google.spanner.admin.database.v1.RestoreSourceType|keyof typeof google.spanner.admin.database.v1.RestoreSourceType|null); /** RestoreInfo backupInfo */ backupInfo?: (google.spanner.admin.database.v1.IBackupInfo|null); } /** Represents a RestoreInfo. */ class RestoreInfo implements IRestoreInfo { /** * Constructs a new RestoreInfo. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IRestoreInfo); /** RestoreInfo sourceType. */ public sourceType: (google.spanner.admin.database.v1.RestoreSourceType|keyof typeof google.spanner.admin.database.v1.RestoreSourceType); /** RestoreInfo backupInfo. */ public backupInfo?: (google.spanner.admin.database.v1.IBackupInfo|null); /** RestoreInfo sourceInfo. */ public sourceInfo?: "backupInfo"; /** * Creates a new RestoreInfo instance using the specified properties. * @param [properties] Properties to set * @returns RestoreInfo instance */ public static create(properties?: google.spanner.admin.database.v1.IRestoreInfo): google.spanner.admin.database.v1.RestoreInfo; /** * Encodes the specified RestoreInfo message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreInfo.verify|verify} messages. * @param message RestoreInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IRestoreInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified RestoreInfo message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreInfo.verify|verify} messages. * @param message RestoreInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IRestoreInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a RestoreInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns RestoreInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.RestoreInfo; /** * Decodes a RestoreInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns RestoreInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.RestoreInfo; /** * Verifies a RestoreInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a RestoreInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns RestoreInfo */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.RestoreInfo; /** * Creates a plain object from a RestoreInfo message. Also converts values to other types if specified. * @param message RestoreInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.RestoreInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this RestoreInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Database. */ interface IDatabase { /** Database name */ name?: (string|null); /** Database state */ state?: (google.spanner.admin.database.v1.Database.State|keyof typeof google.spanner.admin.database.v1.Database.State|null); /** Database createTime */ createTime?: (google.protobuf.ITimestamp|null); /** Database restoreInfo */ restoreInfo?: (google.spanner.admin.database.v1.IRestoreInfo|null); } /** Represents a Database. */ class Database implements IDatabase { /** * Constructs a new Database. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IDatabase); /** Database name. */ public name: string; /** Database state. */ public state: (google.spanner.admin.database.v1.Database.State|keyof typeof google.spanner.admin.database.v1.Database.State); /** Database createTime. */ public createTime?: (google.protobuf.ITimestamp|null); /** Database restoreInfo. */ public restoreInfo?: (google.spanner.admin.database.v1.IRestoreInfo|null); /** * Creates a new Database instance using the specified properties. * @param [properties] Properties to set * @returns Database instance */ public static create(properties?: google.spanner.admin.database.v1.IDatabase): google.spanner.admin.database.v1.Database; /** * Encodes the specified Database message. Does not implicitly {@link google.spanner.admin.database.v1.Database.verify|verify} messages. * @param message Database message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IDatabase, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Database message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.Database.verify|verify} messages. * @param message Database message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IDatabase, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Database message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Database * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.Database; /** * Decodes a Database message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Database * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.Database; /** * Verifies a Database message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Database message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Database */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.Database; /** * Creates a plain object from a Database message. Also converts values to other types if specified. * @param message Database * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.Database, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Database to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Database { /** State enum. */ enum State { STATE_UNSPECIFIED = 0, CREATING = 1, READY = 2, READY_OPTIMIZING = 3 } } /** Properties of a ListDatabasesRequest. */ interface IListDatabasesRequest { /** ListDatabasesRequest parent */ parent?: (string|null); /** ListDatabasesRequest pageSize */ pageSize?: (number|null); /** ListDatabasesRequest pageToken */ pageToken?: (string|null); } /** Represents a ListDatabasesRequest. */ class ListDatabasesRequest implements IListDatabasesRequest { /** * Constructs a new ListDatabasesRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IListDatabasesRequest); /** ListDatabasesRequest parent. */ public parent: string; /** ListDatabasesRequest pageSize. */ public pageSize: number; /** ListDatabasesRequest pageToken. */ public pageToken: string; /** * Creates a new ListDatabasesRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListDatabasesRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IListDatabasesRequest): google.spanner.admin.database.v1.ListDatabasesRequest; /** * Encodes the specified ListDatabasesRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesRequest.verify|verify} messages. * @param message ListDatabasesRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IListDatabasesRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListDatabasesRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesRequest.verify|verify} messages. * @param message ListDatabasesRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IListDatabasesRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListDatabasesRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListDatabasesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListDatabasesRequest; /** * Decodes a ListDatabasesRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListDatabasesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListDatabasesRequest; /** * Verifies a ListDatabasesRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListDatabasesRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListDatabasesRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListDatabasesRequest; /** * Creates a plain object from a ListDatabasesRequest message. Also converts values to other types if specified. * @param message ListDatabasesRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.ListDatabasesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListDatabasesRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListDatabasesResponse. */ interface IListDatabasesResponse { /** ListDatabasesResponse databases */ databases?: (google.spanner.admin.database.v1.IDatabase[]|null); /** ListDatabasesResponse nextPageToken */ nextPageToken?: (string|null); } /** Represents a ListDatabasesResponse. */ class ListDatabasesResponse implements IListDatabasesResponse { /** * Constructs a new ListDatabasesResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IListDatabasesResponse); /** ListDatabasesResponse databases. */ public databases: google.spanner.admin.database.v1.IDatabase[]; /** ListDatabasesResponse nextPageToken. */ public nextPageToken: string; /** * Creates a new ListDatabasesResponse instance using the specified properties. * @param [properties] Properties to set * @returns ListDatabasesResponse instance */ public static create(properties?: google.spanner.admin.database.v1.IListDatabasesResponse): google.spanner.admin.database.v1.ListDatabasesResponse; /** * Encodes the specified ListDatabasesResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesResponse.verify|verify} messages. * @param message ListDatabasesResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IListDatabasesResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListDatabasesResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabasesResponse.verify|verify} messages. * @param message ListDatabasesResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IListDatabasesResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListDatabasesResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListDatabasesResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListDatabasesResponse; /** * Decodes a ListDatabasesResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListDatabasesResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListDatabasesResponse; /** * Verifies a ListDatabasesResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListDatabasesResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListDatabasesResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListDatabasesResponse; /** * Creates a plain object from a ListDatabasesResponse message. Also converts values to other types if specified. * @param message ListDatabasesResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.ListDatabasesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListDatabasesResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CreateDatabaseRequest. */ interface ICreateDatabaseRequest { /** CreateDatabaseRequest parent */ parent?: (string|null); /** CreateDatabaseRequest createStatement */ createStatement?: (string|null); /** CreateDatabaseRequest extraStatements */ extraStatements?: (string[]|null); } /** Represents a CreateDatabaseRequest. */ class CreateDatabaseRequest implements ICreateDatabaseRequest { /** * Constructs a new CreateDatabaseRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.ICreateDatabaseRequest); /** CreateDatabaseRequest parent. */ public parent: string; /** CreateDatabaseRequest createStatement. */ public createStatement: string; /** CreateDatabaseRequest extraStatements. */ public extraStatements: string[]; /** * Creates a new CreateDatabaseRequest instance using the specified properties. * @param [properties] Properties to set * @returns CreateDatabaseRequest instance */ public static create(properties?: google.spanner.admin.database.v1.ICreateDatabaseRequest): google.spanner.admin.database.v1.CreateDatabaseRequest; /** * Encodes the specified CreateDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseRequest.verify|verify} messages. * @param message CreateDatabaseRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.ICreateDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CreateDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseRequest.verify|verify} messages. * @param message CreateDatabaseRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.ICreateDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CreateDatabaseRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CreateDatabaseRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CreateDatabaseRequest; /** * Decodes a CreateDatabaseRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CreateDatabaseRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CreateDatabaseRequest; /** * Verifies a CreateDatabaseRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CreateDatabaseRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CreateDatabaseRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CreateDatabaseRequest; /** * Creates a plain object from a CreateDatabaseRequest message. Also converts values to other types if specified. * @param message CreateDatabaseRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.CreateDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CreateDatabaseRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CreateDatabaseMetadata. */ interface ICreateDatabaseMetadata { /** CreateDatabaseMetadata database */ database?: (string|null); } /** Represents a CreateDatabaseMetadata. */ class CreateDatabaseMetadata implements ICreateDatabaseMetadata { /** * Constructs a new CreateDatabaseMetadata. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.ICreateDatabaseMetadata); /** CreateDatabaseMetadata database. */ public database: string; /** * Creates a new CreateDatabaseMetadata instance using the specified properties. * @param [properties] Properties to set * @returns CreateDatabaseMetadata instance */ public static create(properties?: google.spanner.admin.database.v1.ICreateDatabaseMetadata): google.spanner.admin.database.v1.CreateDatabaseMetadata; /** * Encodes the specified CreateDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseMetadata.verify|verify} messages. * @param message CreateDatabaseMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.ICreateDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CreateDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateDatabaseMetadata.verify|verify} messages. * @param message CreateDatabaseMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.ICreateDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CreateDatabaseMetadata message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CreateDatabaseMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CreateDatabaseMetadata; /** * Decodes a CreateDatabaseMetadata message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CreateDatabaseMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CreateDatabaseMetadata; /** * Verifies a CreateDatabaseMetadata message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CreateDatabaseMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CreateDatabaseMetadata */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CreateDatabaseMetadata; /** * Creates a plain object from a CreateDatabaseMetadata message. Also converts values to other types if specified. * @param message CreateDatabaseMetadata * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.CreateDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CreateDatabaseMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetDatabaseRequest. */ interface IGetDatabaseRequest { /** GetDatabaseRequest name */ name?: (string|null); } /** Represents a GetDatabaseRequest. */ class GetDatabaseRequest implements IGetDatabaseRequest { /** * Constructs a new GetDatabaseRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IGetDatabaseRequest); /** GetDatabaseRequest name. */ public name: string; /** * Creates a new GetDatabaseRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetDatabaseRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IGetDatabaseRequest): google.spanner.admin.database.v1.GetDatabaseRequest; /** * Encodes the specified GetDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseRequest.verify|verify} messages. * @param message GetDatabaseRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IGetDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseRequest.verify|verify} messages. * @param message GetDatabaseRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IGetDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetDatabaseRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetDatabaseRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.GetDatabaseRequest; /** * Decodes a GetDatabaseRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetDatabaseRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.GetDatabaseRequest; /** * Verifies a GetDatabaseRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetDatabaseRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetDatabaseRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.GetDatabaseRequest; /** * Creates a plain object from a GetDatabaseRequest message. Also converts values to other types if specified. * @param message GetDatabaseRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.GetDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetDatabaseRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an UpdateDatabaseDdlRequest. */ interface IUpdateDatabaseDdlRequest { /** UpdateDatabaseDdlRequest database */ database?: (string|null); /** UpdateDatabaseDdlRequest statements */ statements?: (string[]|null); /** UpdateDatabaseDdlRequest operationId */ operationId?: (string|null); } /** Represents an UpdateDatabaseDdlRequest. */ class UpdateDatabaseDdlRequest implements IUpdateDatabaseDdlRequest { /** * Constructs a new UpdateDatabaseDdlRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest); /** UpdateDatabaseDdlRequest database. */ public database: string; /** UpdateDatabaseDdlRequest statements. */ public statements: string[]; /** UpdateDatabaseDdlRequest operationId. */ public operationId: string; /** * Creates a new UpdateDatabaseDdlRequest instance using the specified properties. * @param [properties] Properties to set * @returns UpdateDatabaseDdlRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest): google.spanner.admin.database.v1.UpdateDatabaseDdlRequest; /** * Encodes the specified UpdateDatabaseDdlRequest message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.verify|verify} messages. * @param message UpdateDatabaseDdlRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified UpdateDatabaseDdlRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.verify|verify} messages. * @param message UpdateDatabaseDdlRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IUpdateDatabaseDdlRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an UpdateDatabaseDdlRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns UpdateDatabaseDdlRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.UpdateDatabaseDdlRequest; /** * Decodes an UpdateDatabaseDdlRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns UpdateDatabaseDdlRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.UpdateDatabaseDdlRequest; /** * Verifies an UpdateDatabaseDdlRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an UpdateDatabaseDdlRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns UpdateDatabaseDdlRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.UpdateDatabaseDdlRequest; /** * Creates a plain object from an UpdateDatabaseDdlRequest message. Also converts values to other types if specified. * @param message UpdateDatabaseDdlRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.UpdateDatabaseDdlRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this UpdateDatabaseDdlRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an UpdateDatabaseDdlMetadata. */ interface IUpdateDatabaseDdlMetadata { /** UpdateDatabaseDdlMetadata database */ database?: (string|null); /** UpdateDatabaseDdlMetadata statements */ statements?: (string[]|null); /** UpdateDatabaseDdlMetadata commitTimestamps */ commitTimestamps?: (google.protobuf.ITimestamp[]|null); } /** Represents an UpdateDatabaseDdlMetadata. */ class UpdateDatabaseDdlMetadata implements IUpdateDatabaseDdlMetadata { /** * Constructs a new UpdateDatabaseDdlMetadata. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata); /** UpdateDatabaseDdlMetadata database. */ public database: string; /** UpdateDatabaseDdlMetadata statements. */ public statements: string[]; /** UpdateDatabaseDdlMetadata commitTimestamps. */ public commitTimestamps: google.protobuf.ITimestamp[]; /** * Creates a new UpdateDatabaseDdlMetadata instance using the specified properties. * @param [properties] Properties to set * @returns UpdateDatabaseDdlMetadata instance */ public static create(properties?: google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata): google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; /** * Encodes the specified UpdateDatabaseDdlMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.verify|verify} messages. * @param message UpdateDatabaseDdlMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified UpdateDatabaseDdlMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.verify|verify} messages. * @param message UpdateDatabaseDdlMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IUpdateDatabaseDdlMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an UpdateDatabaseDdlMetadata message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns UpdateDatabaseDdlMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; /** * Decodes an UpdateDatabaseDdlMetadata message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns UpdateDatabaseDdlMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; /** * Verifies an UpdateDatabaseDdlMetadata message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an UpdateDatabaseDdlMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns UpdateDatabaseDdlMetadata */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; /** * Creates a plain object from an UpdateDatabaseDdlMetadata message. Also converts values to other types if specified. * @param message UpdateDatabaseDdlMetadata * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this UpdateDatabaseDdlMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DropDatabaseRequest. */ interface IDropDatabaseRequest { /** DropDatabaseRequest database */ database?: (string|null); } /** Represents a DropDatabaseRequest. */ class DropDatabaseRequest implements IDropDatabaseRequest { /** * Constructs a new DropDatabaseRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IDropDatabaseRequest); /** DropDatabaseRequest database. */ public database: string; /** * Creates a new DropDatabaseRequest instance using the specified properties. * @param [properties] Properties to set * @returns DropDatabaseRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IDropDatabaseRequest): google.spanner.admin.database.v1.DropDatabaseRequest; /** * Encodes the specified DropDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.DropDatabaseRequest.verify|verify} messages. * @param message DropDatabaseRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IDropDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DropDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DropDatabaseRequest.verify|verify} messages. * @param message DropDatabaseRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IDropDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DropDatabaseRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DropDatabaseRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.DropDatabaseRequest; /** * Decodes a DropDatabaseRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DropDatabaseRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.DropDatabaseRequest; /** * Verifies a DropDatabaseRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DropDatabaseRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DropDatabaseRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.DropDatabaseRequest; /** * Creates a plain object from a DropDatabaseRequest message. Also converts values to other types if specified. * @param message DropDatabaseRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.DropDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DropDatabaseRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetDatabaseDdlRequest. */ interface IGetDatabaseDdlRequest { /** GetDatabaseDdlRequest database */ database?: (string|null); } /** Represents a GetDatabaseDdlRequest. */ class GetDatabaseDdlRequest implements IGetDatabaseDdlRequest { /** * Constructs a new GetDatabaseDdlRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IGetDatabaseDdlRequest); /** GetDatabaseDdlRequest database. */ public database: string; /** * Creates a new GetDatabaseDdlRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetDatabaseDdlRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IGetDatabaseDdlRequest): google.spanner.admin.database.v1.GetDatabaseDdlRequest; /** * Encodes the specified GetDatabaseDdlRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlRequest.verify|verify} messages. * @param message GetDatabaseDdlRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IGetDatabaseDdlRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetDatabaseDdlRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlRequest.verify|verify} messages. * @param message GetDatabaseDdlRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IGetDatabaseDdlRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetDatabaseDdlRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetDatabaseDdlRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.GetDatabaseDdlRequest; /** * Decodes a GetDatabaseDdlRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetDatabaseDdlRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.GetDatabaseDdlRequest; /** * Verifies a GetDatabaseDdlRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetDatabaseDdlRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetDatabaseDdlRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.GetDatabaseDdlRequest; /** * Creates a plain object from a GetDatabaseDdlRequest message. Also converts values to other types if specified. * @param message GetDatabaseDdlRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.GetDatabaseDdlRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetDatabaseDdlRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetDatabaseDdlResponse. */ interface IGetDatabaseDdlResponse { /** GetDatabaseDdlResponse statements */ statements?: (string[]|null); } /** Represents a GetDatabaseDdlResponse. */ class GetDatabaseDdlResponse implements IGetDatabaseDdlResponse { /** * Constructs a new GetDatabaseDdlResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IGetDatabaseDdlResponse); /** GetDatabaseDdlResponse statements. */ public statements: string[]; /** * Creates a new GetDatabaseDdlResponse instance using the specified properties. * @param [properties] Properties to set * @returns GetDatabaseDdlResponse instance */ public static create(properties?: google.spanner.admin.database.v1.IGetDatabaseDdlResponse): google.spanner.admin.database.v1.GetDatabaseDdlResponse; /** * Encodes the specified GetDatabaseDdlResponse message. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlResponse.verify|verify} messages. * @param message GetDatabaseDdlResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IGetDatabaseDdlResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetDatabaseDdlResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetDatabaseDdlResponse.verify|verify} messages. * @param message GetDatabaseDdlResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IGetDatabaseDdlResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetDatabaseDdlResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetDatabaseDdlResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.GetDatabaseDdlResponse; /** * Decodes a GetDatabaseDdlResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetDatabaseDdlResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.GetDatabaseDdlResponse; /** * Verifies a GetDatabaseDdlResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetDatabaseDdlResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetDatabaseDdlResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.GetDatabaseDdlResponse; /** * Creates a plain object from a GetDatabaseDdlResponse message. Also converts values to other types if specified. * @param message GetDatabaseDdlResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.GetDatabaseDdlResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetDatabaseDdlResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListDatabaseOperationsRequest. */ interface IListDatabaseOperationsRequest { /** ListDatabaseOperationsRequest parent */ parent?: (string|null); /** ListDatabaseOperationsRequest filter */ filter?: (string|null); /** ListDatabaseOperationsRequest pageSize */ pageSize?: (number|null); /** ListDatabaseOperationsRequest pageToken */ pageToken?: (string|null); } /** Represents a ListDatabaseOperationsRequest. */ class ListDatabaseOperationsRequest implements IListDatabaseOperationsRequest { /** * Constructs a new ListDatabaseOperationsRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IListDatabaseOperationsRequest); /** ListDatabaseOperationsRequest parent. */ public parent: string; /** ListDatabaseOperationsRequest filter. */ public filter: string; /** ListDatabaseOperationsRequest pageSize. */ public pageSize: number; /** ListDatabaseOperationsRequest pageToken. */ public pageToken: string; /** * Creates a new ListDatabaseOperationsRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListDatabaseOperationsRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IListDatabaseOperationsRequest): google.spanner.admin.database.v1.ListDatabaseOperationsRequest; /** * Encodes the specified ListDatabaseOperationsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsRequest.verify|verify} messages. * @param message ListDatabaseOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IListDatabaseOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListDatabaseOperationsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsRequest.verify|verify} messages. * @param message ListDatabaseOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IListDatabaseOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListDatabaseOperationsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListDatabaseOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListDatabaseOperationsRequest; /** * Decodes a ListDatabaseOperationsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListDatabaseOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListDatabaseOperationsRequest; /** * Verifies a ListDatabaseOperationsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListDatabaseOperationsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListDatabaseOperationsRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListDatabaseOperationsRequest; /** * Creates a plain object from a ListDatabaseOperationsRequest message. Also converts values to other types if specified. * @param message ListDatabaseOperationsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.ListDatabaseOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListDatabaseOperationsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListDatabaseOperationsResponse. */ interface IListDatabaseOperationsResponse { /** ListDatabaseOperationsResponse operations */ operations?: (google.longrunning.IOperation[]|null); /** ListDatabaseOperationsResponse nextPageToken */ nextPageToken?: (string|null); } /** Represents a ListDatabaseOperationsResponse. */ class ListDatabaseOperationsResponse implements IListDatabaseOperationsResponse { /** * Constructs a new ListDatabaseOperationsResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IListDatabaseOperationsResponse); /** ListDatabaseOperationsResponse operations. */ public operations: google.longrunning.IOperation[]; /** ListDatabaseOperationsResponse nextPageToken. */ public nextPageToken: string; /** * Creates a new ListDatabaseOperationsResponse instance using the specified properties. * @param [properties] Properties to set * @returns ListDatabaseOperationsResponse instance */ public static create(properties?: google.spanner.admin.database.v1.IListDatabaseOperationsResponse): google.spanner.admin.database.v1.ListDatabaseOperationsResponse; /** * Encodes the specified ListDatabaseOperationsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsResponse.verify|verify} messages. * @param message ListDatabaseOperationsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IListDatabaseOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListDatabaseOperationsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListDatabaseOperationsResponse.verify|verify} messages. * @param message ListDatabaseOperationsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IListDatabaseOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListDatabaseOperationsResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListDatabaseOperationsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListDatabaseOperationsResponse; /** * Decodes a ListDatabaseOperationsResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListDatabaseOperationsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListDatabaseOperationsResponse; /** * Verifies a ListDatabaseOperationsResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListDatabaseOperationsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListDatabaseOperationsResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListDatabaseOperationsResponse; /** * Creates a plain object from a ListDatabaseOperationsResponse message. Also converts values to other types if specified. * @param message ListDatabaseOperationsResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.ListDatabaseOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListDatabaseOperationsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a RestoreDatabaseRequest. */ interface IRestoreDatabaseRequest { /** RestoreDatabaseRequest parent */ parent?: (string|null); /** RestoreDatabaseRequest databaseId */ databaseId?: (string|null); /** RestoreDatabaseRequest backup */ backup?: (string|null); } /** Represents a RestoreDatabaseRequest. */ class RestoreDatabaseRequest implements IRestoreDatabaseRequest { /** * Constructs a new RestoreDatabaseRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IRestoreDatabaseRequest); /** RestoreDatabaseRequest parent. */ public parent: string; /** RestoreDatabaseRequest databaseId. */ public databaseId: string; /** RestoreDatabaseRequest backup. */ public backup: string; /** RestoreDatabaseRequest source. */ public source?: "backup"; /** * Creates a new RestoreDatabaseRequest instance using the specified properties. * @param [properties] Properties to set * @returns RestoreDatabaseRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IRestoreDatabaseRequest): google.spanner.admin.database.v1.RestoreDatabaseRequest; /** * Encodes the specified RestoreDatabaseRequest message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseRequest.verify|verify} messages. * @param message RestoreDatabaseRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IRestoreDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified RestoreDatabaseRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseRequest.verify|verify} messages. * @param message RestoreDatabaseRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IRestoreDatabaseRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a RestoreDatabaseRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns RestoreDatabaseRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.RestoreDatabaseRequest; /** * Decodes a RestoreDatabaseRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns RestoreDatabaseRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.RestoreDatabaseRequest; /** * Verifies a RestoreDatabaseRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a RestoreDatabaseRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns RestoreDatabaseRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.RestoreDatabaseRequest; /** * Creates a plain object from a RestoreDatabaseRequest message. Also converts values to other types if specified. * @param message RestoreDatabaseRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.RestoreDatabaseRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this RestoreDatabaseRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a RestoreDatabaseMetadata. */ interface IRestoreDatabaseMetadata { /** RestoreDatabaseMetadata name */ name?: (string|null); /** RestoreDatabaseMetadata sourceType */ sourceType?: (google.spanner.admin.database.v1.RestoreSourceType|keyof typeof google.spanner.admin.database.v1.RestoreSourceType|null); /** RestoreDatabaseMetadata backupInfo */ backupInfo?: (google.spanner.admin.database.v1.IBackupInfo|null); /** RestoreDatabaseMetadata progress */ progress?: (google.spanner.admin.database.v1.IOperationProgress|null); /** RestoreDatabaseMetadata cancelTime */ cancelTime?: (google.protobuf.ITimestamp|null); /** RestoreDatabaseMetadata optimizeDatabaseOperationName */ optimizeDatabaseOperationName?: (string|null); } /** Represents a RestoreDatabaseMetadata. */ class RestoreDatabaseMetadata implements IRestoreDatabaseMetadata { /** * Constructs a new RestoreDatabaseMetadata. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IRestoreDatabaseMetadata); /** RestoreDatabaseMetadata name. */ public name: string; /** RestoreDatabaseMetadata sourceType. */ public sourceType: (google.spanner.admin.database.v1.RestoreSourceType|keyof typeof google.spanner.admin.database.v1.RestoreSourceType); /** RestoreDatabaseMetadata backupInfo. */ public backupInfo?: (google.spanner.admin.database.v1.IBackupInfo|null); /** RestoreDatabaseMetadata progress. */ public progress?: (google.spanner.admin.database.v1.IOperationProgress|null); /** RestoreDatabaseMetadata cancelTime. */ public cancelTime?: (google.protobuf.ITimestamp|null); /** RestoreDatabaseMetadata optimizeDatabaseOperationName. */ public optimizeDatabaseOperationName: string; /** RestoreDatabaseMetadata sourceInfo. */ public sourceInfo?: "backupInfo"; /** * Creates a new RestoreDatabaseMetadata instance using the specified properties. * @param [properties] Properties to set * @returns RestoreDatabaseMetadata instance */ public static create(properties?: google.spanner.admin.database.v1.IRestoreDatabaseMetadata): google.spanner.admin.database.v1.RestoreDatabaseMetadata; /** * Encodes the specified RestoreDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseMetadata.verify|verify} messages. * @param message RestoreDatabaseMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IRestoreDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified RestoreDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.RestoreDatabaseMetadata.verify|verify} messages. * @param message RestoreDatabaseMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IRestoreDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a RestoreDatabaseMetadata message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns RestoreDatabaseMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.RestoreDatabaseMetadata; /** * Decodes a RestoreDatabaseMetadata message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns RestoreDatabaseMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.RestoreDatabaseMetadata; /** * Verifies a RestoreDatabaseMetadata message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a RestoreDatabaseMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns RestoreDatabaseMetadata */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.RestoreDatabaseMetadata; /** * Creates a plain object from a RestoreDatabaseMetadata message. Also converts values to other types if specified. * @param message RestoreDatabaseMetadata * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.RestoreDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this RestoreDatabaseMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an OptimizeRestoredDatabaseMetadata. */ interface IOptimizeRestoredDatabaseMetadata { /** OptimizeRestoredDatabaseMetadata name */ name?: (string|null); /** OptimizeRestoredDatabaseMetadata progress */ progress?: (google.spanner.admin.database.v1.IOperationProgress|null); } /** Represents an OptimizeRestoredDatabaseMetadata. */ class OptimizeRestoredDatabaseMetadata implements IOptimizeRestoredDatabaseMetadata { /** * Constructs a new OptimizeRestoredDatabaseMetadata. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata); /** OptimizeRestoredDatabaseMetadata name. */ public name: string; /** OptimizeRestoredDatabaseMetadata progress. */ public progress?: (google.spanner.admin.database.v1.IOperationProgress|null); /** * Creates a new OptimizeRestoredDatabaseMetadata instance using the specified properties. * @param [properties] Properties to set * @returns OptimizeRestoredDatabaseMetadata instance */ public static create(properties?: google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata): google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata; /** * Encodes the specified OptimizeRestoredDatabaseMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata.verify|verify} messages. * @param message OptimizeRestoredDatabaseMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OptimizeRestoredDatabaseMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata.verify|verify} messages. * @param message OptimizeRestoredDatabaseMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IOptimizeRestoredDatabaseMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OptimizeRestoredDatabaseMetadata message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OptimizeRestoredDatabaseMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata; /** * Decodes an OptimizeRestoredDatabaseMetadata message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OptimizeRestoredDatabaseMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata; /** * Verifies an OptimizeRestoredDatabaseMetadata message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OptimizeRestoredDatabaseMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OptimizeRestoredDatabaseMetadata */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata; /** * Creates a plain object from an OptimizeRestoredDatabaseMetadata message. Also converts values to other types if specified. * @param message OptimizeRestoredDatabaseMetadata * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OptimizeRestoredDatabaseMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** RestoreSourceType enum. */ enum RestoreSourceType { TYPE_UNSPECIFIED = 0, BACKUP = 1 } /** Properties of a Backup. */ interface IBackup { /** Backup database */ database?: (string|null); /** Backup expireTime */ expireTime?: (google.protobuf.ITimestamp|null); /** Backup name */ name?: (string|null); /** Backup createTime */ createTime?: (google.protobuf.ITimestamp|null); /** Backup sizeBytes */ sizeBytes?: (number|Long|string|null); /** Backup state */ state?: (google.spanner.admin.database.v1.Backup.State|keyof typeof google.spanner.admin.database.v1.Backup.State|null); /** Backup referencingDatabases */ referencingDatabases?: (string[]|null); } /** Represents a Backup. */ class Backup implements IBackup { /** * Constructs a new Backup. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IBackup); /** Backup database. */ public database: string; /** Backup expireTime. */ public expireTime?: (google.protobuf.ITimestamp|null); /** Backup name. */ public name: string; /** Backup createTime. */ public createTime?: (google.protobuf.ITimestamp|null); /** Backup sizeBytes. */ public sizeBytes: (number|Long|string); /** Backup state. */ public state: (google.spanner.admin.database.v1.Backup.State|keyof typeof google.spanner.admin.database.v1.Backup.State); /** Backup referencingDatabases. */ public referencingDatabases: string[]; /** * Creates a new Backup instance using the specified properties. * @param [properties] Properties to set * @returns Backup instance */ public static create(properties?: google.spanner.admin.database.v1.IBackup): google.spanner.admin.database.v1.Backup; /** * Encodes the specified Backup message. Does not implicitly {@link google.spanner.admin.database.v1.Backup.verify|verify} messages. * @param message Backup message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IBackup, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Backup message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.Backup.verify|verify} messages. * @param message Backup message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IBackup, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Backup message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Backup * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.Backup; /** * Decodes a Backup message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Backup * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.Backup; /** * Verifies a Backup message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Backup message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Backup */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.Backup; /** * Creates a plain object from a Backup message. Also converts values to other types if specified. * @param message Backup * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.Backup, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Backup to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Backup { /** State enum. */ enum State { STATE_UNSPECIFIED = 0, CREATING = 1, READY = 2 } } /** Properties of a CreateBackupRequest. */ interface ICreateBackupRequest { /** CreateBackupRequest parent */ parent?: (string|null); /** CreateBackupRequest backupId */ backupId?: (string|null); /** CreateBackupRequest backup */ backup?: (google.spanner.admin.database.v1.IBackup|null); } /** Represents a CreateBackupRequest. */ class CreateBackupRequest implements ICreateBackupRequest { /** * Constructs a new CreateBackupRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.ICreateBackupRequest); /** CreateBackupRequest parent. */ public parent: string; /** CreateBackupRequest backupId. */ public backupId: string; /** CreateBackupRequest backup. */ public backup?: (google.spanner.admin.database.v1.IBackup|null); /** * Creates a new CreateBackupRequest instance using the specified properties. * @param [properties] Properties to set * @returns CreateBackupRequest instance */ public static create(properties?: google.spanner.admin.database.v1.ICreateBackupRequest): google.spanner.admin.database.v1.CreateBackupRequest; /** * Encodes the specified CreateBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupRequest.verify|verify} messages. * @param message CreateBackupRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.ICreateBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CreateBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupRequest.verify|verify} messages. * @param message CreateBackupRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.ICreateBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CreateBackupRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CreateBackupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CreateBackupRequest; /** * Decodes a CreateBackupRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CreateBackupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CreateBackupRequest; /** * Verifies a CreateBackupRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CreateBackupRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CreateBackupRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CreateBackupRequest; /** * Creates a plain object from a CreateBackupRequest message. Also converts values to other types if specified. * @param message CreateBackupRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.CreateBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CreateBackupRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CreateBackupMetadata. */ interface ICreateBackupMetadata { /** CreateBackupMetadata name */ name?: (string|null); /** CreateBackupMetadata database */ database?: (string|null); /** CreateBackupMetadata progress */ progress?: (google.spanner.admin.database.v1.IOperationProgress|null); /** CreateBackupMetadata cancelTime */ cancelTime?: (google.protobuf.ITimestamp|null); } /** Represents a CreateBackupMetadata. */ class CreateBackupMetadata implements ICreateBackupMetadata { /** * Constructs a new CreateBackupMetadata. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.ICreateBackupMetadata); /** CreateBackupMetadata name. */ public name: string; /** CreateBackupMetadata database. */ public database: string; /** CreateBackupMetadata progress. */ public progress?: (google.spanner.admin.database.v1.IOperationProgress|null); /** CreateBackupMetadata cancelTime. */ public cancelTime?: (google.protobuf.ITimestamp|null); /** * Creates a new CreateBackupMetadata instance using the specified properties. * @param [properties] Properties to set * @returns CreateBackupMetadata instance */ public static create(properties?: google.spanner.admin.database.v1.ICreateBackupMetadata): google.spanner.admin.database.v1.CreateBackupMetadata; /** * Encodes the specified CreateBackupMetadata message. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupMetadata.verify|verify} messages. * @param message CreateBackupMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.ICreateBackupMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CreateBackupMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.CreateBackupMetadata.verify|verify} messages. * @param message CreateBackupMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.ICreateBackupMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CreateBackupMetadata message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CreateBackupMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.CreateBackupMetadata; /** * Decodes a CreateBackupMetadata message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CreateBackupMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.CreateBackupMetadata; /** * Verifies a CreateBackupMetadata message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CreateBackupMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CreateBackupMetadata */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.CreateBackupMetadata; /** * Creates a plain object from a CreateBackupMetadata message. Also converts values to other types if specified. * @param message CreateBackupMetadata * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.CreateBackupMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CreateBackupMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an UpdateBackupRequest. */ interface IUpdateBackupRequest { /** UpdateBackupRequest backup */ backup?: (google.spanner.admin.database.v1.IBackup|null); /** UpdateBackupRequest updateMask */ updateMask?: (google.protobuf.IFieldMask|null); } /** Represents an UpdateBackupRequest. */ class UpdateBackupRequest implements IUpdateBackupRequest { /** * Constructs a new UpdateBackupRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IUpdateBackupRequest); /** UpdateBackupRequest backup. */ public backup?: (google.spanner.admin.database.v1.IBackup|null); /** UpdateBackupRequest updateMask. */ public updateMask?: (google.protobuf.IFieldMask|null); /** * Creates a new UpdateBackupRequest instance using the specified properties. * @param [properties] Properties to set * @returns UpdateBackupRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IUpdateBackupRequest): google.spanner.admin.database.v1.UpdateBackupRequest; /** * Encodes the specified UpdateBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.UpdateBackupRequest.verify|verify} messages. * @param message UpdateBackupRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IUpdateBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified UpdateBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.UpdateBackupRequest.verify|verify} messages. * @param message UpdateBackupRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IUpdateBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an UpdateBackupRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns UpdateBackupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.UpdateBackupRequest; /** * Decodes an UpdateBackupRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns UpdateBackupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.UpdateBackupRequest; /** * Verifies an UpdateBackupRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an UpdateBackupRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns UpdateBackupRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.UpdateBackupRequest; /** * Creates a plain object from an UpdateBackupRequest message. Also converts values to other types if specified. * @param message UpdateBackupRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.UpdateBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this UpdateBackupRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetBackupRequest. */ interface IGetBackupRequest { /** GetBackupRequest name */ name?: (string|null); } /** Represents a GetBackupRequest. */ class GetBackupRequest implements IGetBackupRequest { /** * Constructs a new GetBackupRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IGetBackupRequest); /** GetBackupRequest name. */ public name: string; /** * Creates a new GetBackupRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetBackupRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IGetBackupRequest): google.spanner.admin.database.v1.GetBackupRequest; /** * Encodes the specified GetBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.GetBackupRequest.verify|verify} messages. * @param message GetBackupRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IGetBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.GetBackupRequest.verify|verify} messages. * @param message GetBackupRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IGetBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetBackupRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetBackupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.GetBackupRequest; /** * Decodes a GetBackupRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetBackupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.GetBackupRequest; /** * Verifies a GetBackupRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetBackupRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetBackupRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.GetBackupRequest; /** * Creates a plain object from a GetBackupRequest message. Also converts values to other types if specified. * @param message GetBackupRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.GetBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetBackupRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteBackupRequest. */ interface IDeleteBackupRequest { /** DeleteBackupRequest name */ name?: (string|null); } /** Represents a DeleteBackupRequest. */ class DeleteBackupRequest implements IDeleteBackupRequest { /** * Constructs a new DeleteBackupRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IDeleteBackupRequest); /** DeleteBackupRequest name. */ public name: string; /** * Creates a new DeleteBackupRequest instance using the specified properties. * @param [properties] Properties to set * @returns DeleteBackupRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IDeleteBackupRequest): google.spanner.admin.database.v1.DeleteBackupRequest; /** * Encodes the specified DeleteBackupRequest message. Does not implicitly {@link google.spanner.admin.database.v1.DeleteBackupRequest.verify|verify} messages. * @param message DeleteBackupRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IDeleteBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteBackupRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.DeleteBackupRequest.verify|verify} messages. * @param message DeleteBackupRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IDeleteBackupRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteBackupRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteBackupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.DeleteBackupRequest; /** * Decodes a DeleteBackupRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteBackupRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.DeleteBackupRequest; /** * Verifies a DeleteBackupRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteBackupRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteBackupRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.DeleteBackupRequest; /** * Creates a plain object from a DeleteBackupRequest message. Also converts values to other types if specified. * @param message DeleteBackupRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.DeleteBackupRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteBackupRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListBackupsRequest. */ interface IListBackupsRequest { /** ListBackupsRequest parent */ parent?: (string|null); /** ListBackupsRequest filter */ filter?: (string|null); /** ListBackupsRequest pageSize */ pageSize?: (number|null); /** ListBackupsRequest pageToken */ pageToken?: (string|null); } /** Represents a ListBackupsRequest. */ class ListBackupsRequest implements IListBackupsRequest { /** * Constructs a new ListBackupsRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IListBackupsRequest); /** ListBackupsRequest parent. */ public parent: string; /** ListBackupsRequest filter. */ public filter: string; /** ListBackupsRequest pageSize. */ public pageSize: number; /** ListBackupsRequest pageToken. */ public pageToken: string; /** * Creates a new ListBackupsRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListBackupsRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IListBackupsRequest): google.spanner.admin.database.v1.ListBackupsRequest; /** * Encodes the specified ListBackupsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsRequest.verify|verify} messages. * @param message ListBackupsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IListBackupsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListBackupsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsRequest.verify|verify} messages. * @param message ListBackupsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IListBackupsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListBackupsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListBackupsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListBackupsRequest; /** * Decodes a ListBackupsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListBackupsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListBackupsRequest; /** * Verifies a ListBackupsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListBackupsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListBackupsRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListBackupsRequest; /** * Creates a plain object from a ListBackupsRequest message. Also converts values to other types if specified. * @param message ListBackupsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.ListBackupsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListBackupsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListBackupsResponse. */ interface IListBackupsResponse { /** ListBackupsResponse backups */ backups?: (google.spanner.admin.database.v1.IBackup[]|null); /** ListBackupsResponse nextPageToken */ nextPageToken?: (string|null); } /** Represents a ListBackupsResponse. */ class ListBackupsResponse implements IListBackupsResponse { /** * Constructs a new ListBackupsResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IListBackupsResponse); /** ListBackupsResponse backups. */ public backups: google.spanner.admin.database.v1.IBackup[]; /** ListBackupsResponse nextPageToken. */ public nextPageToken: string; /** * Creates a new ListBackupsResponse instance using the specified properties. * @param [properties] Properties to set * @returns ListBackupsResponse instance */ public static create(properties?: google.spanner.admin.database.v1.IListBackupsResponse): google.spanner.admin.database.v1.ListBackupsResponse; /** * Encodes the specified ListBackupsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsResponse.verify|verify} messages. * @param message ListBackupsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IListBackupsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListBackupsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupsResponse.verify|verify} messages. * @param message ListBackupsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IListBackupsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListBackupsResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListBackupsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListBackupsResponse; /** * Decodes a ListBackupsResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListBackupsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListBackupsResponse; /** * Verifies a ListBackupsResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListBackupsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListBackupsResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListBackupsResponse; /** * Creates a plain object from a ListBackupsResponse message. Also converts values to other types if specified. * @param message ListBackupsResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.ListBackupsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListBackupsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListBackupOperationsRequest. */ interface IListBackupOperationsRequest { /** ListBackupOperationsRequest parent */ parent?: (string|null); /** ListBackupOperationsRequest filter */ filter?: (string|null); /** ListBackupOperationsRequest pageSize */ pageSize?: (number|null); /** ListBackupOperationsRequest pageToken */ pageToken?: (string|null); } /** Represents a ListBackupOperationsRequest. */ class ListBackupOperationsRequest implements IListBackupOperationsRequest { /** * Constructs a new ListBackupOperationsRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IListBackupOperationsRequest); /** ListBackupOperationsRequest parent. */ public parent: string; /** ListBackupOperationsRequest filter. */ public filter: string; /** ListBackupOperationsRequest pageSize. */ public pageSize: number; /** ListBackupOperationsRequest pageToken. */ public pageToken: string; /** * Creates a new ListBackupOperationsRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListBackupOperationsRequest instance */ public static create(properties?: google.spanner.admin.database.v1.IListBackupOperationsRequest): google.spanner.admin.database.v1.ListBackupOperationsRequest; /** * Encodes the specified ListBackupOperationsRequest message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsRequest.verify|verify} messages. * @param message ListBackupOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IListBackupOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListBackupOperationsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsRequest.verify|verify} messages. * @param message ListBackupOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IListBackupOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListBackupOperationsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListBackupOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListBackupOperationsRequest; /** * Decodes a ListBackupOperationsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListBackupOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListBackupOperationsRequest; /** * Verifies a ListBackupOperationsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListBackupOperationsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListBackupOperationsRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListBackupOperationsRequest; /** * Creates a plain object from a ListBackupOperationsRequest message. Also converts values to other types if specified. * @param message ListBackupOperationsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.ListBackupOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListBackupOperationsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListBackupOperationsResponse. */ interface IListBackupOperationsResponse { /** ListBackupOperationsResponse operations */ operations?: (google.longrunning.IOperation[]|null); /** ListBackupOperationsResponse nextPageToken */ nextPageToken?: (string|null); } /** Represents a ListBackupOperationsResponse. */ class ListBackupOperationsResponse implements IListBackupOperationsResponse { /** * Constructs a new ListBackupOperationsResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IListBackupOperationsResponse); /** ListBackupOperationsResponse operations. */ public operations: google.longrunning.IOperation[]; /** ListBackupOperationsResponse nextPageToken. */ public nextPageToken: string; /** * Creates a new ListBackupOperationsResponse instance using the specified properties. * @param [properties] Properties to set * @returns ListBackupOperationsResponse instance */ public static create(properties?: google.spanner.admin.database.v1.IListBackupOperationsResponse): google.spanner.admin.database.v1.ListBackupOperationsResponse; /** * Encodes the specified ListBackupOperationsResponse message. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsResponse.verify|verify} messages. * @param message ListBackupOperationsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IListBackupOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListBackupOperationsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.ListBackupOperationsResponse.verify|verify} messages. * @param message ListBackupOperationsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IListBackupOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListBackupOperationsResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListBackupOperationsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.ListBackupOperationsResponse; /** * Decodes a ListBackupOperationsResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListBackupOperationsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.ListBackupOperationsResponse; /** * Verifies a ListBackupOperationsResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListBackupOperationsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListBackupOperationsResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.ListBackupOperationsResponse; /** * Creates a plain object from a ListBackupOperationsResponse message. Also converts values to other types if specified. * @param message ListBackupOperationsResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.ListBackupOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListBackupOperationsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BackupInfo. */ interface IBackupInfo { /** BackupInfo backup */ backup?: (string|null); /** BackupInfo createTime */ createTime?: (google.protobuf.ITimestamp|null); /** BackupInfo sourceDatabase */ sourceDatabase?: (string|null); } /** Represents a BackupInfo. */ class BackupInfo implements IBackupInfo { /** * Constructs a new BackupInfo. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IBackupInfo); /** BackupInfo backup. */ public backup: string; /** BackupInfo createTime. */ public createTime?: (google.protobuf.ITimestamp|null); /** BackupInfo sourceDatabase. */ public sourceDatabase: string; /** * Creates a new BackupInfo instance using the specified properties. * @param [properties] Properties to set * @returns BackupInfo instance */ public static create(properties?: google.spanner.admin.database.v1.IBackupInfo): google.spanner.admin.database.v1.BackupInfo; /** * Encodes the specified BackupInfo message. Does not implicitly {@link google.spanner.admin.database.v1.BackupInfo.verify|verify} messages. * @param message BackupInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IBackupInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BackupInfo message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.BackupInfo.verify|verify} messages. * @param message BackupInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IBackupInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BackupInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BackupInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.BackupInfo; /** * Decodes a BackupInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BackupInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.BackupInfo; /** * Verifies a BackupInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BackupInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BackupInfo */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.BackupInfo; /** * Creates a plain object from a BackupInfo message. Also converts values to other types if specified. * @param message BackupInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.BackupInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BackupInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an OperationProgress. */ interface IOperationProgress { /** OperationProgress progressPercent */ progressPercent?: (number|null); /** OperationProgress startTime */ startTime?: (google.protobuf.ITimestamp|null); /** OperationProgress endTime */ endTime?: (google.protobuf.ITimestamp|null); } /** Represents an OperationProgress. */ class OperationProgress implements IOperationProgress { /** * Constructs a new OperationProgress. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.database.v1.IOperationProgress); /** OperationProgress progressPercent. */ public progressPercent: number; /** OperationProgress startTime. */ public startTime?: (google.protobuf.ITimestamp|null); /** OperationProgress endTime. */ public endTime?: (google.protobuf.ITimestamp|null); /** * Creates a new OperationProgress instance using the specified properties. * @param [properties] Properties to set * @returns OperationProgress instance */ public static create(properties?: google.spanner.admin.database.v1.IOperationProgress): google.spanner.admin.database.v1.OperationProgress; /** * Encodes the specified OperationProgress message. Does not implicitly {@link google.spanner.admin.database.v1.OperationProgress.verify|verify} messages. * @param message OperationProgress message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.database.v1.IOperationProgress, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OperationProgress message, length delimited. Does not implicitly {@link google.spanner.admin.database.v1.OperationProgress.verify|verify} messages. * @param message OperationProgress message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.database.v1.IOperationProgress, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OperationProgress message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OperationProgress * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.database.v1.OperationProgress; /** * Decodes an OperationProgress message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OperationProgress * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.database.v1.OperationProgress; /** * Verifies an OperationProgress message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OperationProgress message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OperationProgress */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.database.v1.OperationProgress; /** * Creates a plain object from an OperationProgress message. Also converts values to other types if specified. * @param message OperationProgress * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.database.v1.OperationProgress, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OperationProgress to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace instance. */ namespace instance { /** Namespace v1. */ namespace v1 { /** Represents an InstanceAdmin */ class InstanceAdmin extends $protobuf.rpc.Service { /** * Constructs a new InstanceAdmin service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new InstanceAdmin service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): InstanceAdmin; /** * Calls ListInstanceConfigs. * @param request ListInstanceConfigsRequest message or plain object * @param callback Node-style callback called with the error, if any, and ListInstanceConfigsResponse */ public listInstanceConfigs(request: google.spanner.admin.instance.v1.IListInstanceConfigsRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigsCallback): void; /** * Calls ListInstanceConfigs. * @param request ListInstanceConfigsRequest message or plain object * @returns Promise */ public listInstanceConfigs(request: google.spanner.admin.instance.v1.IListInstanceConfigsRequest): Promise<google.spanner.admin.instance.v1.ListInstanceConfigsResponse>; /** * Calls GetInstanceConfig. * @param request GetInstanceConfigRequest message or plain object * @param callback Node-style callback called with the error, if any, and InstanceConfig */ public getInstanceConfig(request: google.spanner.admin.instance.v1.IGetInstanceConfigRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfigCallback): void; /** * Calls GetInstanceConfig. * @param request GetInstanceConfigRequest message or plain object * @returns Promise */ public getInstanceConfig(request: google.spanner.admin.instance.v1.IGetInstanceConfigRequest): Promise<google.spanner.admin.instance.v1.InstanceConfig>; /** * Calls ListInstances. * @param request ListInstancesRequest message or plain object * @param callback Node-style callback called with the error, if any, and ListInstancesResponse */ public listInstances(request: google.spanner.admin.instance.v1.IListInstancesRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.ListInstancesCallback): void; /** * Calls ListInstances. * @param request ListInstancesRequest message or plain object * @returns Promise */ public listInstances(request: google.spanner.admin.instance.v1.IListInstancesRequest): Promise<google.spanner.admin.instance.v1.ListInstancesResponse>; /** * Calls GetInstance. * @param request GetInstanceRequest message or plain object * @param callback Node-style callback called with the error, if any, and Instance */ public getInstance(request: google.spanner.admin.instance.v1.IGetInstanceRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceCallback): void; /** * Calls GetInstance. * @param request GetInstanceRequest message or plain object * @returns Promise */ public getInstance(request: google.spanner.admin.instance.v1.IGetInstanceRequest): Promise<google.spanner.admin.instance.v1.Instance>; /** * Calls CreateInstance. * @param request CreateInstanceRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public createInstance(request: google.spanner.admin.instance.v1.ICreateInstanceRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.CreateInstanceCallback): void; /** * Calls CreateInstance. * @param request CreateInstanceRequest message or plain object * @returns Promise */ public createInstance(request: google.spanner.admin.instance.v1.ICreateInstanceRequest): Promise<google.longrunning.Operation>; /** * Calls UpdateInstance. * @param request UpdateInstanceRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public updateInstance(request: google.spanner.admin.instance.v1.IUpdateInstanceRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstanceCallback): void; /** * Calls UpdateInstance. * @param request UpdateInstanceRequest message or plain object * @returns Promise */ public updateInstance(request: google.spanner.admin.instance.v1.IUpdateInstanceRequest): Promise<google.longrunning.Operation>; /** * Calls DeleteInstance. * @param request DeleteInstanceRequest message or plain object * @param callback Node-style callback called with the error, if any, and Empty */ public deleteInstance(request: google.spanner.admin.instance.v1.IDeleteInstanceRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstanceCallback): void; /** * Calls DeleteInstance. * @param request DeleteInstanceRequest message or plain object * @returns Promise */ public deleteInstance(request: google.spanner.admin.instance.v1.IDeleteInstanceRequest): Promise<google.protobuf.Empty>; /** * Calls SetIamPolicy. * @param request SetIamPolicyRequest message or plain object * @param callback Node-style callback called with the error, if any, and Policy */ public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.SetIamPolicyCallback): void; /** * Calls SetIamPolicy. * @param request SetIamPolicyRequest message or plain object * @returns Promise */ public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest): Promise<google.iam.v1.Policy>; /** * Calls GetIamPolicy. * @param request GetIamPolicyRequest message or plain object * @param callback Node-style callback called with the error, if any, and Policy */ public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.GetIamPolicyCallback): void; /** * Calls GetIamPolicy. * @param request GetIamPolicyRequest message or plain object * @returns Promise */ public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest): Promise<google.iam.v1.Policy>; /** * Calls TestIamPermissions. * @param request TestIamPermissionsRequest message or plain object * @param callback Node-style callback called with the error, if any, and TestIamPermissionsResponse */ public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest, callback: google.spanner.admin.instance.v1.InstanceAdmin.TestIamPermissionsCallback): void; /** * Calls TestIamPermissions. * @param request TestIamPermissionsRequest message or plain object * @returns Promise */ public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest): Promise<google.iam.v1.TestIamPermissionsResponse>; } namespace InstanceAdmin { /** * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin#listInstanceConfigs}. * @param error Error, if any * @param [response] ListInstanceConfigsResponse */ type ListInstanceConfigsCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.ListInstanceConfigsResponse) => void; /** * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin#getInstanceConfig}. * @param error Error, if any * @param [response] InstanceConfig */ type GetInstanceConfigCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.InstanceConfig) => void; /** * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin#listInstances}. * @param error Error, if any * @param [response] ListInstancesResponse */ type ListInstancesCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.ListInstancesResponse) => void; /** * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin#getInstance}. * @param error Error, if any * @param [response] Instance */ type GetInstanceCallback = (error: (Error|null), response?: google.spanner.admin.instance.v1.Instance) => void; /** * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin#createInstance}. * @param error Error, if any * @param [response] Operation */ type CreateInstanceCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; /** * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin#updateInstance}. * @param error Error, if any * @param [response] Operation */ type UpdateInstanceCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; /** * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin#deleteInstance}. * @param error Error, if any * @param [response] Empty */ type DeleteInstanceCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; /** * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin#setIamPolicy}. * @param error Error, if any * @param [response] Policy */ type SetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; /** * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin#getIamPolicy}. * @param error Error, if any * @param [response] Policy */ type GetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; /** * Callback as used by {@link google.spanner.admin.instance.v1.InstanceAdmin#testIamPermissions}. * @param error Error, if any * @param [response] TestIamPermissionsResponse */ type TestIamPermissionsCallback = (error: (Error|null), response?: google.iam.v1.TestIamPermissionsResponse) => void; } /** Properties of a ReplicaInfo. */ interface IReplicaInfo { /** ReplicaInfo location */ location?: (string|null); /** ReplicaInfo type */ type?: (google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType|keyof typeof google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType|null); /** ReplicaInfo defaultLeaderLocation */ defaultLeaderLocation?: (boolean|null); } /** Represents a ReplicaInfo. */ class ReplicaInfo implements IReplicaInfo { /** * Constructs a new ReplicaInfo. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IReplicaInfo); /** ReplicaInfo location. */ public location: string; /** ReplicaInfo type. */ public type: (google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType|keyof typeof google.spanner.admin.instance.v1.ReplicaInfo.ReplicaType); /** ReplicaInfo defaultLeaderLocation. */ public defaultLeaderLocation: boolean; /** * Creates a new ReplicaInfo instance using the specified properties. * @param [properties] Properties to set * @returns ReplicaInfo instance */ public static create(properties?: google.spanner.admin.instance.v1.IReplicaInfo): google.spanner.admin.instance.v1.ReplicaInfo; /** * Encodes the specified ReplicaInfo message. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaInfo.verify|verify} messages. * @param message ReplicaInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IReplicaInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ReplicaInfo message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ReplicaInfo.verify|verify} messages. * @param message ReplicaInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IReplicaInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ReplicaInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ReplicaInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ReplicaInfo; /** * Decodes a ReplicaInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ReplicaInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ReplicaInfo; /** * Verifies a ReplicaInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ReplicaInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ReplicaInfo */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ReplicaInfo; /** * Creates a plain object from a ReplicaInfo message. Also converts values to other types if specified. * @param message ReplicaInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.ReplicaInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ReplicaInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace ReplicaInfo { /** ReplicaType enum. */ enum ReplicaType { TYPE_UNSPECIFIED = 0, READ_WRITE = 1, READ_ONLY = 2, WITNESS = 3 } } /** Properties of an InstanceConfig. */ interface IInstanceConfig { /** InstanceConfig name */ name?: (string|null); /** InstanceConfig displayName */ displayName?: (string|null); /** InstanceConfig replicas */ replicas?: (google.spanner.admin.instance.v1.IReplicaInfo[]|null); } /** Represents an InstanceConfig. */ class InstanceConfig implements IInstanceConfig { /** * Constructs a new InstanceConfig. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IInstanceConfig); /** InstanceConfig name. */ public name: string; /** InstanceConfig displayName. */ public displayName: string; /** InstanceConfig replicas. */ public replicas: google.spanner.admin.instance.v1.IReplicaInfo[]; /** * Creates a new InstanceConfig instance using the specified properties. * @param [properties] Properties to set * @returns InstanceConfig instance */ public static create(properties?: google.spanner.admin.instance.v1.IInstanceConfig): google.spanner.admin.instance.v1.InstanceConfig; /** * Encodes the specified InstanceConfig message. Does not implicitly {@link google.spanner.admin.instance.v1.InstanceConfig.verify|verify} messages. * @param message InstanceConfig message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IInstanceConfig, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified InstanceConfig message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.InstanceConfig.verify|verify} messages. * @param message InstanceConfig message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IInstanceConfig, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an InstanceConfig message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns InstanceConfig * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.InstanceConfig; /** * Decodes an InstanceConfig message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns InstanceConfig * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.InstanceConfig; /** * Verifies an InstanceConfig message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an InstanceConfig message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns InstanceConfig */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.InstanceConfig; /** * Creates a plain object from an InstanceConfig message. Also converts values to other types if specified. * @param message InstanceConfig * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.InstanceConfig, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this InstanceConfig to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Instance. */ interface IInstance { /** Instance name */ name?: (string|null); /** Instance config */ config?: (string|null); /** Instance displayName */ displayName?: (string|null); /** Instance nodeCount */ nodeCount?: (number|null); /** Instance state */ state?: (google.spanner.admin.instance.v1.Instance.State|keyof typeof google.spanner.admin.instance.v1.Instance.State|null); /** Instance labels */ labels?: ({ [k: string]: string }|null); /** Instance endpointUris */ endpointUris?: (string[]|null); } /** Represents an Instance. */ class Instance implements IInstance { /** * Constructs a new Instance. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IInstance); /** Instance name. */ public name: string; /** Instance config. */ public config: string; /** Instance displayName. */ public displayName: string; /** Instance nodeCount. */ public nodeCount: number; /** Instance state. */ public state: (google.spanner.admin.instance.v1.Instance.State|keyof typeof google.spanner.admin.instance.v1.Instance.State); /** Instance labels. */ public labels: { [k: string]: string }; /** Instance endpointUris. */ public endpointUris: string[]; /** * Creates a new Instance instance using the specified properties. * @param [properties] Properties to set * @returns Instance instance */ public static create(properties?: google.spanner.admin.instance.v1.IInstance): google.spanner.admin.instance.v1.Instance; /** * Encodes the specified Instance message. Does not implicitly {@link google.spanner.admin.instance.v1.Instance.verify|verify} messages. * @param message Instance message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IInstance, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Instance message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.Instance.verify|verify} messages. * @param message Instance message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IInstance, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Instance message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Instance * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.Instance; /** * Decodes an Instance message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Instance * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.Instance; /** * Verifies an Instance message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Instance message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Instance */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.Instance; /** * Creates a plain object from an Instance message. Also converts values to other types if specified. * @param message Instance * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.Instance, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Instance to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Instance { /** State enum. */ enum State { STATE_UNSPECIFIED = 0, CREATING = 1, READY = 2 } } /** Properties of a ListInstanceConfigsRequest. */ interface IListInstanceConfigsRequest { /** ListInstanceConfigsRequest parent */ parent?: (string|null); /** ListInstanceConfigsRequest pageSize */ pageSize?: (number|null); /** ListInstanceConfigsRequest pageToken */ pageToken?: (string|null); } /** Represents a ListInstanceConfigsRequest. */ class ListInstanceConfigsRequest implements IListInstanceConfigsRequest { /** * Constructs a new ListInstanceConfigsRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IListInstanceConfigsRequest); /** ListInstanceConfigsRequest parent. */ public parent: string; /** ListInstanceConfigsRequest pageSize. */ public pageSize: number; /** ListInstanceConfigsRequest pageToken. */ public pageToken: string; /** * Creates a new ListInstanceConfigsRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListInstanceConfigsRequest instance */ public static create(properties?: google.spanner.admin.instance.v1.IListInstanceConfigsRequest): google.spanner.admin.instance.v1.ListInstanceConfigsRequest; /** * Encodes the specified ListInstanceConfigsRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsRequest.verify|verify} messages. * @param message ListInstanceConfigsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IListInstanceConfigsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListInstanceConfigsRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsRequest.verify|verify} messages. * @param message ListInstanceConfigsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstanceConfigsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListInstanceConfigsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListInstanceConfigsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstanceConfigsRequest; /** * Decodes a ListInstanceConfigsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListInstanceConfigsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstanceConfigsRequest; /** * Verifies a ListInstanceConfigsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListInstanceConfigsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListInstanceConfigsRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstanceConfigsRequest; /** * Creates a plain object from a ListInstanceConfigsRequest message. Also converts values to other types if specified. * @param message ListInstanceConfigsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.ListInstanceConfigsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListInstanceConfigsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListInstanceConfigsResponse. */ interface IListInstanceConfigsResponse { /** ListInstanceConfigsResponse instanceConfigs */ instanceConfigs?: (google.spanner.admin.instance.v1.IInstanceConfig[]|null); /** ListInstanceConfigsResponse nextPageToken */ nextPageToken?: (string|null); } /** Represents a ListInstanceConfigsResponse. */ class ListInstanceConfigsResponse implements IListInstanceConfigsResponse { /** * Constructs a new ListInstanceConfigsResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IListInstanceConfigsResponse); /** ListInstanceConfigsResponse instanceConfigs. */ public instanceConfigs: google.spanner.admin.instance.v1.IInstanceConfig[]; /** ListInstanceConfigsResponse nextPageToken. */ public nextPageToken: string; /** * Creates a new ListInstanceConfigsResponse instance using the specified properties. * @param [properties] Properties to set * @returns ListInstanceConfigsResponse instance */ public static create(properties?: google.spanner.admin.instance.v1.IListInstanceConfigsResponse): google.spanner.admin.instance.v1.ListInstanceConfigsResponse; /** * Encodes the specified ListInstanceConfigsResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsResponse.verify|verify} messages. * @param message ListInstanceConfigsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IListInstanceConfigsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListInstanceConfigsResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstanceConfigsResponse.verify|verify} messages. * @param message ListInstanceConfigsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstanceConfigsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListInstanceConfigsResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListInstanceConfigsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstanceConfigsResponse; /** * Decodes a ListInstanceConfigsResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListInstanceConfigsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstanceConfigsResponse; /** * Verifies a ListInstanceConfigsResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListInstanceConfigsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListInstanceConfigsResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstanceConfigsResponse; /** * Creates a plain object from a ListInstanceConfigsResponse message. Also converts values to other types if specified. * @param message ListInstanceConfigsResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.ListInstanceConfigsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListInstanceConfigsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetInstanceConfigRequest. */ interface IGetInstanceConfigRequest { /** GetInstanceConfigRequest name */ name?: (string|null); } /** Represents a GetInstanceConfigRequest. */ class GetInstanceConfigRequest implements IGetInstanceConfigRequest { /** * Constructs a new GetInstanceConfigRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IGetInstanceConfigRequest); /** GetInstanceConfigRequest name. */ public name: string; /** * Creates a new GetInstanceConfigRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetInstanceConfigRequest instance */ public static create(properties?: google.spanner.admin.instance.v1.IGetInstanceConfigRequest): google.spanner.admin.instance.v1.GetInstanceConfigRequest; /** * Encodes the specified GetInstanceConfigRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceConfigRequest.verify|verify} messages. * @param message GetInstanceConfigRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IGetInstanceConfigRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetInstanceConfigRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceConfigRequest.verify|verify} messages. * @param message GetInstanceConfigRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IGetInstanceConfigRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetInstanceConfigRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetInstanceConfigRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.GetInstanceConfigRequest; /** * Decodes a GetInstanceConfigRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetInstanceConfigRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.GetInstanceConfigRequest; /** * Verifies a GetInstanceConfigRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetInstanceConfigRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetInstanceConfigRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.GetInstanceConfigRequest; /** * Creates a plain object from a GetInstanceConfigRequest message. Also converts values to other types if specified. * @param message GetInstanceConfigRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.GetInstanceConfigRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetInstanceConfigRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetInstanceRequest. */ interface IGetInstanceRequest { /** GetInstanceRequest name */ name?: (string|null); /** GetInstanceRequest fieldMask */ fieldMask?: (google.protobuf.IFieldMask|null); } /** Represents a GetInstanceRequest. */ class GetInstanceRequest implements IGetInstanceRequest { /** * Constructs a new GetInstanceRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IGetInstanceRequest); /** GetInstanceRequest name. */ public name: string; /** GetInstanceRequest fieldMask. */ public fieldMask?: (google.protobuf.IFieldMask|null); /** * Creates a new GetInstanceRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetInstanceRequest instance */ public static create(properties?: google.spanner.admin.instance.v1.IGetInstanceRequest): google.spanner.admin.instance.v1.GetInstanceRequest; /** * Encodes the specified GetInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceRequest.verify|verify} messages. * @param message GetInstanceRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IGetInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.GetInstanceRequest.verify|verify} messages. * @param message GetInstanceRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IGetInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetInstanceRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetInstanceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.GetInstanceRequest; /** * Decodes a GetInstanceRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetInstanceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.GetInstanceRequest; /** * Verifies a GetInstanceRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetInstanceRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetInstanceRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.GetInstanceRequest; /** * Creates a plain object from a GetInstanceRequest message. Also converts values to other types if specified. * @param message GetInstanceRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.GetInstanceRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetInstanceRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CreateInstanceRequest. */ interface ICreateInstanceRequest { /** CreateInstanceRequest parent */ parent?: (string|null); /** CreateInstanceRequest instanceId */ instanceId?: (string|null); /** CreateInstanceRequest instance */ instance?: (google.spanner.admin.instance.v1.IInstance|null); } /** Represents a CreateInstanceRequest. */ class CreateInstanceRequest implements ICreateInstanceRequest { /** * Constructs a new CreateInstanceRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.ICreateInstanceRequest); /** CreateInstanceRequest parent. */ public parent: string; /** CreateInstanceRequest instanceId. */ public instanceId: string; /** CreateInstanceRequest instance. */ public instance?: (google.spanner.admin.instance.v1.IInstance|null); /** * Creates a new CreateInstanceRequest instance using the specified properties. * @param [properties] Properties to set * @returns CreateInstanceRequest instance */ public static create(properties?: google.spanner.admin.instance.v1.ICreateInstanceRequest): google.spanner.admin.instance.v1.CreateInstanceRequest; /** * Encodes the specified CreateInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceRequest.verify|verify} messages. * @param message CreateInstanceRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.ICreateInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CreateInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceRequest.verify|verify} messages. * @param message CreateInstanceRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.ICreateInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CreateInstanceRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CreateInstanceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.CreateInstanceRequest; /** * Decodes a CreateInstanceRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CreateInstanceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.CreateInstanceRequest; /** * Verifies a CreateInstanceRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CreateInstanceRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CreateInstanceRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.CreateInstanceRequest; /** * Creates a plain object from a CreateInstanceRequest message. Also converts values to other types if specified. * @param message CreateInstanceRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.CreateInstanceRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CreateInstanceRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListInstancesRequest. */ interface IListInstancesRequest { /** ListInstancesRequest parent */ parent?: (string|null); /** ListInstancesRequest pageSize */ pageSize?: (number|null); /** ListInstancesRequest pageToken */ pageToken?: (string|null); /** ListInstancesRequest filter */ filter?: (string|null); } /** Represents a ListInstancesRequest. */ class ListInstancesRequest implements IListInstancesRequest { /** * Constructs a new ListInstancesRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IListInstancesRequest); /** ListInstancesRequest parent. */ public parent: string; /** ListInstancesRequest pageSize. */ public pageSize: number; /** ListInstancesRequest pageToken. */ public pageToken: string; /** ListInstancesRequest filter. */ public filter: string; /** * Creates a new ListInstancesRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListInstancesRequest instance */ public static create(properties?: google.spanner.admin.instance.v1.IListInstancesRequest): google.spanner.admin.instance.v1.ListInstancesRequest; /** * Encodes the specified ListInstancesRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesRequest.verify|verify} messages. * @param message ListInstancesRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IListInstancesRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListInstancesRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesRequest.verify|verify} messages. * @param message ListInstancesRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstancesRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListInstancesRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListInstancesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstancesRequest; /** * Decodes a ListInstancesRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListInstancesRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstancesRequest; /** * Verifies a ListInstancesRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListInstancesRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListInstancesRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstancesRequest; /** * Creates a plain object from a ListInstancesRequest message. Also converts values to other types if specified. * @param message ListInstancesRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.ListInstancesRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListInstancesRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListInstancesResponse. */ interface IListInstancesResponse { /** ListInstancesResponse instances */ instances?: (google.spanner.admin.instance.v1.IInstance[]|null); /** ListInstancesResponse nextPageToken */ nextPageToken?: (string|null); } /** Represents a ListInstancesResponse. */ class ListInstancesResponse implements IListInstancesResponse { /** * Constructs a new ListInstancesResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IListInstancesResponse); /** ListInstancesResponse instances. */ public instances: google.spanner.admin.instance.v1.IInstance[]; /** ListInstancesResponse nextPageToken. */ public nextPageToken: string; /** * Creates a new ListInstancesResponse instance using the specified properties. * @param [properties] Properties to set * @returns ListInstancesResponse instance */ public static create(properties?: google.spanner.admin.instance.v1.IListInstancesResponse): google.spanner.admin.instance.v1.ListInstancesResponse; /** * Encodes the specified ListInstancesResponse message. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesResponse.verify|verify} messages. * @param message ListInstancesResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IListInstancesResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListInstancesResponse message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.ListInstancesResponse.verify|verify} messages. * @param message ListInstancesResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IListInstancesResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListInstancesResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListInstancesResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.ListInstancesResponse; /** * Decodes a ListInstancesResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListInstancesResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.ListInstancesResponse; /** * Verifies a ListInstancesResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListInstancesResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListInstancesResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.ListInstancesResponse; /** * Creates a plain object from a ListInstancesResponse message. Also converts values to other types if specified. * @param message ListInstancesResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.ListInstancesResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListInstancesResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an UpdateInstanceRequest. */ interface IUpdateInstanceRequest { /** UpdateInstanceRequest instance */ instance?: (google.spanner.admin.instance.v1.IInstance|null); /** UpdateInstanceRequest fieldMask */ fieldMask?: (google.protobuf.IFieldMask|null); } /** Represents an UpdateInstanceRequest. */ class UpdateInstanceRequest implements IUpdateInstanceRequest { /** * Constructs a new UpdateInstanceRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IUpdateInstanceRequest); /** UpdateInstanceRequest instance. */ public instance?: (google.spanner.admin.instance.v1.IInstance|null); /** UpdateInstanceRequest fieldMask. */ public fieldMask?: (google.protobuf.IFieldMask|null); /** * Creates a new UpdateInstanceRequest instance using the specified properties. * @param [properties] Properties to set * @returns UpdateInstanceRequest instance */ public static create(properties?: google.spanner.admin.instance.v1.IUpdateInstanceRequest): google.spanner.admin.instance.v1.UpdateInstanceRequest; /** * Encodes the specified UpdateInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceRequest.verify|verify} messages. * @param message UpdateInstanceRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IUpdateInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified UpdateInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceRequest.verify|verify} messages. * @param message UpdateInstanceRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IUpdateInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an UpdateInstanceRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns UpdateInstanceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.UpdateInstanceRequest; /** * Decodes an UpdateInstanceRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns UpdateInstanceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.UpdateInstanceRequest; /** * Verifies an UpdateInstanceRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an UpdateInstanceRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns UpdateInstanceRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.UpdateInstanceRequest; /** * Creates a plain object from an UpdateInstanceRequest message. Also converts values to other types if specified. * @param message UpdateInstanceRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.UpdateInstanceRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this UpdateInstanceRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteInstanceRequest. */ interface IDeleteInstanceRequest { /** DeleteInstanceRequest name */ name?: (string|null); } /** Represents a DeleteInstanceRequest. */ class DeleteInstanceRequest implements IDeleteInstanceRequest { /** * Constructs a new DeleteInstanceRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IDeleteInstanceRequest); /** DeleteInstanceRequest name. */ public name: string; /** * Creates a new DeleteInstanceRequest instance using the specified properties. * @param [properties] Properties to set * @returns DeleteInstanceRequest instance */ public static create(properties?: google.spanner.admin.instance.v1.IDeleteInstanceRequest): google.spanner.admin.instance.v1.DeleteInstanceRequest; /** * Encodes the specified DeleteInstanceRequest message. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstanceRequest.verify|verify} messages. * @param message DeleteInstanceRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IDeleteInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteInstanceRequest message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.DeleteInstanceRequest.verify|verify} messages. * @param message DeleteInstanceRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IDeleteInstanceRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteInstanceRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteInstanceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.DeleteInstanceRequest; /** * Decodes a DeleteInstanceRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteInstanceRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.DeleteInstanceRequest; /** * Verifies a DeleteInstanceRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteInstanceRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteInstanceRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.DeleteInstanceRequest; /** * Creates a plain object from a DeleteInstanceRequest message. Also converts values to other types if specified. * @param message DeleteInstanceRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.DeleteInstanceRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteInstanceRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CreateInstanceMetadata. */ interface ICreateInstanceMetadata { /** CreateInstanceMetadata instance */ instance?: (google.spanner.admin.instance.v1.IInstance|null); /** CreateInstanceMetadata startTime */ startTime?: (google.protobuf.ITimestamp|null); /** CreateInstanceMetadata cancelTime */ cancelTime?: (google.protobuf.ITimestamp|null); /** CreateInstanceMetadata endTime */ endTime?: (google.protobuf.ITimestamp|null); } /** Represents a CreateInstanceMetadata. */ class CreateInstanceMetadata implements ICreateInstanceMetadata { /** * Constructs a new CreateInstanceMetadata. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.ICreateInstanceMetadata); /** CreateInstanceMetadata instance. */ public instance?: (google.spanner.admin.instance.v1.IInstance|null); /** CreateInstanceMetadata startTime. */ public startTime?: (google.protobuf.ITimestamp|null); /** CreateInstanceMetadata cancelTime. */ public cancelTime?: (google.protobuf.ITimestamp|null); /** CreateInstanceMetadata endTime. */ public endTime?: (google.protobuf.ITimestamp|null); /** * Creates a new CreateInstanceMetadata instance using the specified properties. * @param [properties] Properties to set * @returns CreateInstanceMetadata instance */ public static create(properties?: google.spanner.admin.instance.v1.ICreateInstanceMetadata): google.spanner.admin.instance.v1.CreateInstanceMetadata; /** * Encodes the specified CreateInstanceMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceMetadata.verify|verify} messages. * @param message CreateInstanceMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.ICreateInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CreateInstanceMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.CreateInstanceMetadata.verify|verify} messages. * @param message CreateInstanceMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.ICreateInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CreateInstanceMetadata message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CreateInstanceMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.CreateInstanceMetadata; /** * Decodes a CreateInstanceMetadata message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CreateInstanceMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.CreateInstanceMetadata; /** * Verifies a CreateInstanceMetadata message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CreateInstanceMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CreateInstanceMetadata */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.CreateInstanceMetadata; /** * Creates a plain object from a CreateInstanceMetadata message. Also converts values to other types if specified. * @param message CreateInstanceMetadata * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.CreateInstanceMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CreateInstanceMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an UpdateInstanceMetadata. */ interface IUpdateInstanceMetadata { /** UpdateInstanceMetadata instance */ instance?: (google.spanner.admin.instance.v1.IInstance|null); /** UpdateInstanceMetadata startTime */ startTime?: (google.protobuf.ITimestamp|null); /** UpdateInstanceMetadata cancelTime */ cancelTime?: (google.protobuf.ITimestamp|null); /** UpdateInstanceMetadata endTime */ endTime?: (google.protobuf.ITimestamp|null); } /** Represents an UpdateInstanceMetadata. */ class UpdateInstanceMetadata implements IUpdateInstanceMetadata { /** * Constructs a new UpdateInstanceMetadata. * @param [properties] Properties to set */ constructor(properties?: google.spanner.admin.instance.v1.IUpdateInstanceMetadata); /** UpdateInstanceMetadata instance. */ public instance?: (google.spanner.admin.instance.v1.IInstance|null); /** UpdateInstanceMetadata startTime. */ public startTime?: (google.protobuf.ITimestamp|null); /** UpdateInstanceMetadata cancelTime. */ public cancelTime?: (google.protobuf.ITimestamp|null); /** UpdateInstanceMetadata endTime. */ public endTime?: (google.protobuf.ITimestamp|null); /** * Creates a new UpdateInstanceMetadata instance using the specified properties. * @param [properties] Properties to set * @returns UpdateInstanceMetadata instance */ public static create(properties?: google.spanner.admin.instance.v1.IUpdateInstanceMetadata): google.spanner.admin.instance.v1.UpdateInstanceMetadata; /** * Encodes the specified UpdateInstanceMetadata message. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceMetadata.verify|verify} messages. * @param message UpdateInstanceMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.admin.instance.v1.IUpdateInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified UpdateInstanceMetadata message, length delimited. Does not implicitly {@link google.spanner.admin.instance.v1.UpdateInstanceMetadata.verify|verify} messages. * @param message UpdateInstanceMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.admin.instance.v1.IUpdateInstanceMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an UpdateInstanceMetadata message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns UpdateInstanceMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.admin.instance.v1.UpdateInstanceMetadata; /** * Decodes an UpdateInstanceMetadata message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns UpdateInstanceMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.admin.instance.v1.UpdateInstanceMetadata; /** * Verifies an UpdateInstanceMetadata message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an UpdateInstanceMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns UpdateInstanceMetadata */ public static fromObject(object: { [k: string]: any }): google.spanner.admin.instance.v1.UpdateInstanceMetadata; /** * Creates a plain object from an UpdateInstanceMetadata message. Also converts values to other types if specified. * @param message UpdateInstanceMetadata * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.admin.instance.v1.UpdateInstanceMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this UpdateInstanceMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } } /** Namespace v1. */ namespace v1 { /** Represents a Spanner */ class Spanner extends $protobuf.rpc.Service { /** * Constructs a new Spanner service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new Spanner service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Spanner; /** * Calls CreateSession. * @param request CreateSessionRequest message or plain object * @param callback Node-style callback called with the error, if any, and Session */ public createSession(request: google.spanner.v1.ICreateSessionRequest, callback: google.spanner.v1.Spanner.CreateSessionCallback): void; /** * Calls CreateSession. * @param request CreateSessionRequest message or plain object * @returns Promise */ public createSession(request: google.spanner.v1.ICreateSessionRequest): Promise<google.spanner.v1.Session>; /** * Calls BatchCreateSessions. * @param request BatchCreateSessionsRequest message or plain object * @param callback Node-style callback called with the error, if any, and BatchCreateSessionsResponse */ public batchCreateSessions(request: google.spanner.v1.IBatchCreateSessionsRequest, callback: google.spanner.v1.Spanner.BatchCreateSessionsCallback): void; /** * Calls BatchCreateSessions. * @param request BatchCreateSessionsRequest message or plain object * @returns Promise */ public batchCreateSessions(request: google.spanner.v1.IBatchCreateSessionsRequest): Promise<google.spanner.v1.BatchCreateSessionsResponse>; /** * Calls GetSession. * @param request GetSessionRequest message or plain object * @param callback Node-style callback called with the error, if any, and Session */ public getSession(request: google.spanner.v1.IGetSessionRequest, callback: google.spanner.v1.Spanner.GetSessionCallback): void; /** * Calls GetSession. * @param request GetSessionRequest message or plain object * @returns Promise */ public getSession(request: google.spanner.v1.IGetSessionRequest): Promise<google.spanner.v1.Session>; /** * Calls ListSessions. * @param request ListSessionsRequest message or plain object * @param callback Node-style callback called with the error, if any, and ListSessionsResponse */ public listSessions(request: google.spanner.v1.IListSessionsRequest, callback: google.spanner.v1.Spanner.ListSessionsCallback): void; /** * Calls ListSessions. * @param request ListSessionsRequest message or plain object * @returns Promise */ public listSessions(request: google.spanner.v1.IListSessionsRequest): Promise<google.spanner.v1.ListSessionsResponse>; /** * Calls DeleteSession. * @param request DeleteSessionRequest message or plain object * @param callback Node-style callback called with the error, if any, and Empty */ public deleteSession(request: google.spanner.v1.IDeleteSessionRequest, callback: google.spanner.v1.Spanner.DeleteSessionCallback): void; /** * Calls DeleteSession. * @param request DeleteSessionRequest message or plain object * @returns Promise */ public deleteSession(request: google.spanner.v1.IDeleteSessionRequest): Promise<google.protobuf.Empty>; /** * Calls ExecuteSql. * @param request ExecuteSqlRequest message or plain object * @param callback Node-style callback called with the error, if any, and ResultSet */ public executeSql(request: google.spanner.v1.IExecuteSqlRequest, callback: google.spanner.v1.Spanner.ExecuteSqlCallback): void; /** * Calls ExecuteSql. * @param request ExecuteSqlRequest message or plain object * @returns Promise */ public executeSql(request: google.spanner.v1.IExecuteSqlRequest): Promise<google.spanner.v1.ResultSet>; /** * Calls ExecuteStreamingSql. * @param request ExecuteSqlRequest message or plain object * @param callback Node-style callback called with the error, if any, and PartialResultSet */ public executeStreamingSql(request: google.spanner.v1.IExecuteSqlRequest, callback: google.spanner.v1.Spanner.ExecuteStreamingSqlCallback): void; /** * Calls ExecuteStreamingSql. * @param request ExecuteSqlRequest message or plain object * @returns Promise */ public executeStreamingSql(request: google.spanner.v1.IExecuteSqlRequest): Promise<google.spanner.v1.PartialResultSet>; /** * Calls ExecuteBatchDml. * @param request ExecuteBatchDmlRequest message or plain object * @param callback Node-style callback called with the error, if any, and ExecuteBatchDmlResponse */ public executeBatchDml(request: google.spanner.v1.IExecuteBatchDmlRequest, callback: google.spanner.v1.Spanner.ExecuteBatchDmlCallback): void; /** * Calls ExecuteBatchDml. * @param request ExecuteBatchDmlRequest message or plain object * @returns Promise */ public executeBatchDml(request: google.spanner.v1.IExecuteBatchDmlRequest): Promise<google.spanner.v1.ExecuteBatchDmlResponse>; /** * Calls Read. * @param request ReadRequest message or plain object * @param callback Node-style callback called with the error, if any, and ResultSet */ public read(request: google.spanner.v1.IReadRequest, callback: google.spanner.v1.Spanner.ReadCallback): void; /** * Calls Read. * @param request ReadRequest message or plain object * @returns Promise */ public read(request: google.spanner.v1.IReadRequest): Promise<google.spanner.v1.ResultSet>; /** * Calls StreamingRead. * @param request ReadRequest message or plain object * @param callback Node-style callback called with the error, if any, and PartialResultSet */ public streamingRead(request: google.spanner.v1.IReadRequest, callback: google.spanner.v1.Spanner.StreamingReadCallback): void; /** * Calls StreamingRead. * @param request ReadRequest message or plain object * @returns Promise */ public streamingRead(request: google.spanner.v1.IReadRequest): Promise<google.spanner.v1.PartialResultSet>; /** * Calls BeginTransaction. * @param request BeginTransactionRequest message or plain object * @param callback Node-style callback called with the error, if any, and Transaction */ public beginTransaction(request: google.spanner.v1.IBeginTransactionRequest, callback: google.spanner.v1.Spanner.BeginTransactionCallback): void; /** * Calls BeginTransaction. * @param request BeginTransactionRequest message or plain object * @returns Promise */ public beginTransaction(request: google.spanner.v1.IBeginTransactionRequest): Promise<google.spanner.v1.Transaction>; /** * Calls Commit. * @param request CommitRequest message or plain object * @param callback Node-style callback called with the error, if any, and CommitResponse */ public commit(request: google.spanner.v1.ICommitRequest, callback: google.spanner.v1.Spanner.CommitCallback): void; /** * Calls Commit. * @param request CommitRequest message or plain object * @returns Promise */ public commit(request: google.spanner.v1.ICommitRequest): Promise<google.spanner.v1.CommitResponse>; /** * Calls Rollback. * @param request RollbackRequest message or plain object * @param callback Node-style callback called with the error, if any, and Empty */ public rollback(request: google.spanner.v1.IRollbackRequest, callback: google.spanner.v1.Spanner.RollbackCallback): void; /** * Calls Rollback. * @param request RollbackRequest message or plain object * @returns Promise */ public rollback(request: google.spanner.v1.IRollbackRequest): Promise<google.protobuf.Empty>; /** * Calls PartitionQuery. * @param request PartitionQueryRequest message or plain object * @param callback Node-style callback called with the error, if any, and PartitionResponse */ public partitionQuery(request: google.spanner.v1.IPartitionQueryRequest, callback: google.spanner.v1.Spanner.PartitionQueryCallback): void; /** * Calls PartitionQuery. * @param request PartitionQueryRequest message or plain object * @returns Promise */ public partitionQuery(request: google.spanner.v1.IPartitionQueryRequest): Promise<google.spanner.v1.PartitionResponse>; /** * Calls PartitionRead. * @param request PartitionReadRequest message or plain object * @param callback Node-style callback called with the error, if any, and PartitionResponse */ public partitionRead(request: google.spanner.v1.IPartitionReadRequest, callback: google.spanner.v1.Spanner.PartitionReadCallback): void; /** * Calls PartitionRead. * @param request PartitionReadRequest message or plain object * @returns Promise */ public partitionRead(request: google.spanner.v1.IPartitionReadRequest): Promise<google.spanner.v1.PartitionResponse>; } namespace Spanner { /** * Callback as used by {@link google.spanner.v1.Spanner#createSession}. * @param error Error, if any * @param [response] Session */ type CreateSessionCallback = (error: (Error|null), response?: google.spanner.v1.Session) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#batchCreateSessions}. * @param error Error, if any * @param [response] BatchCreateSessionsResponse */ type BatchCreateSessionsCallback = (error: (Error|null), response?: google.spanner.v1.BatchCreateSessionsResponse) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#getSession}. * @param error Error, if any * @param [response] Session */ type GetSessionCallback = (error: (Error|null), response?: google.spanner.v1.Session) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#listSessions}. * @param error Error, if any * @param [response] ListSessionsResponse */ type ListSessionsCallback = (error: (Error|null), response?: google.spanner.v1.ListSessionsResponse) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#deleteSession}. * @param error Error, if any * @param [response] Empty */ type DeleteSessionCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#executeSql}. * @param error Error, if any * @param [response] ResultSet */ type ExecuteSqlCallback = (error: (Error|null), response?: google.spanner.v1.ResultSet) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#executeStreamingSql}. * @param error Error, if any * @param [response] PartialResultSet */ type ExecuteStreamingSqlCallback = (error: (Error|null), response?: google.spanner.v1.PartialResultSet) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#executeBatchDml}. * @param error Error, if any * @param [response] ExecuteBatchDmlResponse */ type ExecuteBatchDmlCallback = (error: (Error|null), response?: google.spanner.v1.ExecuteBatchDmlResponse) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#read}. * @param error Error, if any * @param [response] ResultSet */ type ReadCallback = (error: (Error|null), response?: google.spanner.v1.ResultSet) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#streamingRead}. * @param error Error, if any * @param [response] PartialResultSet */ type StreamingReadCallback = (error: (Error|null), response?: google.spanner.v1.PartialResultSet) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#beginTransaction}. * @param error Error, if any * @param [response] Transaction */ type BeginTransactionCallback = (error: (Error|null), response?: google.spanner.v1.Transaction) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#commit}. * @param error Error, if any * @param [response] CommitResponse */ type CommitCallback = (error: (Error|null), response?: google.spanner.v1.CommitResponse) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#rollback}. * @param error Error, if any * @param [response] Empty */ type RollbackCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#partitionQuery}. * @param error Error, if any * @param [response] PartitionResponse */ type PartitionQueryCallback = (error: (Error|null), response?: google.spanner.v1.PartitionResponse) => void; /** * Callback as used by {@link google.spanner.v1.Spanner#partitionRead}. * @param error Error, if any * @param [response] PartitionResponse */ type PartitionReadCallback = (error: (Error|null), response?: google.spanner.v1.PartitionResponse) => void; } /** Properties of a CreateSessionRequest. */ interface ICreateSessionRequest { /** CreateSessionRequest database */ database?: (string|null); /** CreateSessionRequest session */ session?: (google.spanner.v1.ISession|null); } /** Represents a CreateSessionRequest. */ class CreateSessionRequest implements ICreateSessionRequest { /** * Constructs a new CreateSessionRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.ICreateSessionRequest); /** CreateSessionRequest database. */ public database: string; /** CreateSessionRequest session. */ public session?: (google.spanner.v1.ISession|null); /** * Creates a new CreateSessionRequest instance using the specified properties. * @param [properties] Properties to set * @returns CreateSessionRequest instance */ public static create(properties?: google.spanner.v1.ICreateSessionRequest): google.spanner.v1.CreateSessionRequest; /** * Encodes the specified CreateSessionRequest message. Does not implicitly {@link google.spanner.v1.CreateSessionRequest.verify|verify} messages. * @param message CreateSessionRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.ICreateSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CreateSessionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.CreateSessionRequest.verify|verify} messages. * @param message CreateSessionRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.ICreateSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CreateSessionRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CreateSessionRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.CreateSessionRequest; /** * Decodes a CreateSessionRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CreateSessionRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.CreateSessionRequest; /** * Verifies a CreateSessionRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CreateSessionRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CreateSessionRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.CreateSessionRequest; /** * Creates a plain object from a CreateSessionRequest message. Also converts values to other types if specified. * @param message CreateSessionRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.CreateSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CreateSessionRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BatchCreateSessionsRequest. */ interface IBatchCreateSessionsRequest { /** BatchCreateSessionsRequest database */ database?: (string|null); /** BatchCreateSessionsRequest sessionTemplate */ sessionTemplate?: (google.spanner.v1.ISession|null); /** BatchCreateSessionsRequest sessionCount */ sessionCount?: (number|null); } /** Represents a BatchCreateSessionsRequest. */ class BatchCreateSessionsRequest implements IBatchCreateSessionsRequest { /** * Constructs a new BatchCreateSessionsRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IBatchCreateSessionsRequest); /** BatchCreateSessionsRequest database. */ public database: string; /** BatchCreateSessionsRequest sessionTemplate. */ public sessionTemplate?: (google.spanner.v1.ISession|null); /** BatchCreateSessionsRequest sessionCount. */ public sessionCount: number; /** * Creates a new BatchCreateSessionsRequest instance using the specified properties. * @param [properties] Properties to set * @returns BatchCreateSessionsRequest instance */ public static create(properties?: google.spanner.v1.IBatchCreateSessionsRequest): google.spanner.v1.BatchCreateSessionsRequest; /** * Encodes the specified BatchCreateSessionsRequest message. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsRequest.verify|verify} messages. * @param message BatchCreateSessionsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IBatchCreateSessionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BatchCreateSessionsRequest message, length delimited. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsRequest.verify|verify} messages. * @param message BatchCreateSessionsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IBatchCreateSessionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BatchCreateSessionsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BatchCreateSessionsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.BatchCreateSessionsRequest; /** * Decodes a BatchCreateSessionsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BatchCreateSessionsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.BatchCreateSessionsRequest; /** * Verifies a BatchCreateSessionsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BatchCreateSessionsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BatchCreateSessionsRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.BatchCreateSessionsRequest; /** * Creates a plain object from a BatchCreateSessionsRequest message. Also converts values to other types if specified. * @param message BatchCreateSessionsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.BatchCreateSessionsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BatchCreateSessionsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BatchCreateSessionsResponse. */ interface IBatchCreateSessionsResponse { /** BatchCreateSessionsResponse session */ session?: (google.spanner.v1.ISession[]|null); } /** Represents a BatchCreateSessionsResponse. */ class BatchCreateSessionsResponse implements IBatchCreateSessionsResponse { /** * Constructs a new BatchCreateSessionsResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IBatchCreateSessionsResponse); /** BatchCreateSessionsResponse session. */ public session: google.spanner.v1.ISession[]; /** * Creates a new BatchCreateSessionsResponse instance using the specified properties. * @param [properties] Properties to set * @returns BatchCreateSessionsResponse instance */ public static create(properties?: google.spanner.v1.IBatchCreateSessionsResponse): google.spanner.v1.BatchCreateSessionsResponse; /** * Encodes the specified BatchCreateSessionsResponse message. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsResponse.verify|verify} messages. * @param message BatchCreateSessionsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IBatchCreateSessionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BatchCreateSessionsResponse message, length delimited. Does not implicitly {@link google.spanner.v1.BatchCreateSessionsResponse.verify|verify} messages. * @param message BatchCreateSessionsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IBatchCreateSessionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BatchCreateSessionsResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BatchCreateSessionsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.BatchCreateSessionsResponse; /** * Decodes a BatchCreateSessionsResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BatchCreateSessionsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.BatchCreateSessionsResponse; /** * Verifies a BatchCreateSessionsResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BatchCreateSessionsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BatchCreateSessionsResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.BatchCreateSessionsResponse; /** * Creates a plain object from a BatchCreateSessionsResponse message. Also converts values to other types if specified. * @param message BatchCreateSessionsResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.BatchCreateSessionsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BatchCreateSessionsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Session. */ interface ISession { /** Session name */ name?: (string|null); /** Session labels */ labels?: ({ [k: string]: string }|null); /** Session createTime */ createTime?: (google.protobuf.ITimestamp|null); /** Session approximateLastUseTime */ approximateLastUseTime?: (google.protobuf.ITimestamp|null); } /** Represents a Session. */ class Session implements ISession { /** * Constructs a new Session. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.ISession); /** Session name. */ public name: string; /** Session labels. */ public labels: { [k: string]: string }; /** Session createTime. */ public createTime?: (google.protobuf.ITimestamp|null); /** Session approximateLastUseTime. */ public approximateLastUseTime?: (google.protobuf.ITimestamp|null); /** * Creates a new Session instance using the specified properties. * @param [properties] Properties to set * @returns Session instance */ public static create(properties?: google.spanner.v1.ISession): google.spanner.v1.Session; /** * Encodes the specified Session message. Does not implicitly {@link google.spanner.v1.Session.verify|verify} messages. * @param message Session message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.ISession, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Session message, length delimited. Does not implicitly {@link google.spanner.v1.Session.verify|verify} messages. * @param message Session message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.ISession, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Session message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Session * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Session; /** * Decodes a Session message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Session * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Session; /** * Verifies a Session message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Session message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Session */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.Session; /** * Creates a plain object from a Session message. Also converts values to other types if specified. * @param message Session * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.Session, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Session to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetSessionRequest. */ interface IGetSessionRequest { /** GetSessionRequest name */ name?: (string|null); } /** Represents a GetSessionRequest. */ class GetSessionRequest implements IGetSessionRequest { /** * Constructs a new GetSessionRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IGetSessionRequest); /** GetSessionRequest name. */ public name: string; /** * Creates a new GetSessionRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetSessionRequest instance */ public static create(properties?: google.spanner.v1.IGetSessionRequest): google.spanner.v1.GetSessionRequest; /** * Encodes the specified GetSessionRequest message. Does not implicitly {@link google.spanner.v1.GetSessionRequest.verify|verify} messages. * @param message GetSessionRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IGetSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetSessionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.GetSessionRequest.verify|verify} messages. * @param message GetSessionRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IGetSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetSessionRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetSessionRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.GetSessionRequest; /** * Decodes a GetSessionRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetSessionRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.GetSessionRequest; /** * Verifies a GetSessionRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetSessionRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetSessionRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.GetSessionRequest; /** * Creates a plain object from a GetSessionRequest message. Also converts values to other types if specified. * @param message GetSessionRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.GetSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetSessionRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListSessionsRequest. */ interface IListSessionsRequest { /** ListSessionsRequest database */ database?: (string|null); /** ListSessionsRequest pageSize */ pageSize?: (number|null); /** ListSessionsRequest pageToken */ pageToken?: (string|null); /** ListSessionsRequest filter */ filter?: (string|null); } /** Represents a ListSessionsRequest. */ class ListSessionsRequest implements IListSessionsRequest { /** * Constructs a new ListSessionsRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IListSessionsRequest); /** ListSessionsRequest database. */ public database: string; /** ListSessionsRequest pageSize. */ public pageSize: number; /** ListSessionsRequest pageToken. */ public pageToken: string; /** ListSessionsRequest filter. */ public filter: string; /** * Creates a new ListSessionsRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListSessionsRequest instance */ public static create(properties?: google.spanner.v1.IListSessionsRequest): google.spanner.v1.ListSessionsRequest; /** * Encodes the specified ListSessionsRequest message. Does not implicitly {@link google.spanner.v1.ListSessionsRequest.verify|verify} messages. * @param message ListSessionsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IListSessionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListSessionsRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ListSessionsRequest.verify|verify} messages. * @param message ListSessionsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IListSessionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListSessionsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListSessionsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ListSessionsRequest; /** * Decodes a ListSessionsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListSessionsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ListSessionsRequest; /** * Verifies a ListSessionsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListSessionsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListSessionsRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ListSessionsRequest; /** * Creates a plain object from a ListSessionsRequest message. Also converts values to other types if specified. * @param message ListSessionsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ListSessionsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListSessionsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListSessionsResponse. */ interface IListSessionsResponse { /** ListSessionsResponse sessions */ sessions?: (google.spanner.v1.ISession[]|null); /** ListSessionsResponse nextPageToken */ nextPageToken?: (string|null); } /** Represents a ListSessionsResponse. */ class ListSessionsResponse implements IListSessionsResponse { /** * Constructs a new ListSessionsResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IListSessionsResponse); /** ListSessionsResponse sessions. */ public sessions: google.spanner.v1.ISession[]; /** ListSessionsResponse nextPageToken. */ public nextPageToken: string; /** * Creates a new ListSessionsResponse instance using the specified properties. * @param [properties] Properties to set * @returns ListSessionsResponse instance */ public static create(properties?: google.spanner.v1.IListSessionsResponse): google.spanner.v1.ListSessionsResponse; /** * Encodes the specified ListSessionsResponse message. Does not implicitly {@link google.spanner.v1.ListSessionsResponse.verify|verify} messages. * @param message ListSessionsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IListSessionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListSessionsResponse message, length delimited. Does not implicitly {@link google.spanner.v1.ListSessionsResponse.verify|verify} messages. * @param message ListSessionsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IListSessionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListSessionsResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListSessionsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ListSessionsResponse; /** * Decodes a ListSessionsResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListSessionsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ListSessionsResponse; /** * Verifies a ListSessionsResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListSessionsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListSessionsResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ListSessionsResponse; /** * Creates a plain object from a ListSessionsResponse message. Also converts values to other types if specified. * @param message ListSessionsResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ListSessionsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListSessionsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteSessionRequest. */ interface IDeleteSessionRequest { /** DeleteSessionRequest name */ name?: (string|null); } /** Represents a DeleteSessionRequest. */ class DeleteSessionRequest implements IDeleteSessionRequest { /** * Constructs a new DeleteSessionRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IDeleteSessionRequest); /** DeleteSessionRequest name. */ public name: string; /** * Creates a new DeleteSessionRequest instance using the specified properties. * @param [properties] Properties to set * @returns DeleteSessionRequest instance */ public static create(properties?: google.spanner.v1.IDeleteSessionRequest): google.spanner.v1.DeleteSessionRequest; /** * Encodes the specified DeleteSessionRequest message. Does not implicitly {@link google.spanner.v1.DeleteSessionRequest.verify|verify} messages. * @param message DeleteSessionRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IDeleteSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteSessionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.DeleteSessionRequest.verify|verify} messages. * @param message DeleteSessionRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IDeleteSessionRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteSessionRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteSessionRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.DeleteSessionRequest; /** * Decodes a DeleteSessionRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteSessionRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.DeleteSessionRequest; /** * Verifies a DeleteSessionRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteSessionRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteSessionRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.DeleteSessionRequest; /** * Creates a plain object from a DeleteSessionRequest message. Also converts values to other types if specified. * @param message DeleteSessionRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.DeleteSessionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteSessionRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an ExecuteSqlRequest. */ interface IExecuteSqlRequest { /** ExecuteSqlRequest session */ session?: (string|null); /** ExecuteSqlRequest transaction */ transaction?: (google.spanner.v1.ITransactionSelector|null); /** ExecuteSqlRequest sql */ sql?: (string|null); /** ExecuteSqlRequest params */ params?: (google.protobuf.IStruct|null); /** ExecuteSqlRequest paramTypes */ paramTypes?: ({ [k: string]: google.spanner.v1.IType }|null); /** ExecuteSqlRequest resumeToken */ resumeToken?: (Uint8Array|string|null); /** ExecuteSqlRequest queryMode */ queryMode?: (google.spanner.v1.ExecuteSqlRequest.QueryMode|keyof typeof google.spanner.v1.ExecuteSqlRequest.QueryMode|null); /** ExecuteSqlRequest partitionToken */ partitionToken?: (Uint8Array|string|null); /** ExecuteSqlRequest seqno */ seqno?: (number|Long|string|null); /** ExecuteSqlRequest queryOptions */ queryOptions?: (google.spanner.v1.ExecuteSqlRequest.IQueryOptions|null); } /** Represents an ExecuteSqlRequest. */ class ExecuteSqlRequest implements IExecuteSqlRequest { /** * Constructs a new ExecuteSqlRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IExecuteSqlRequest); /** ExecuteSqlRequest session. */ public session: string; /** ExecuteSqlRequest transaction. */ public transaction?: (google.spanner.v1.ITransactionSelector|null); /** ExecuteSqlRequest sql. */ public sql: string; /** ExecuteSqlRequest params. */ public params?: (google.protobuf.IStruct|null); /** ExecuteSqlRequest paramTypes. */ public paramTypes: { [k: string]: google.spanner.v1.IType }; /** ExecuteSqlRequest resumeToken. */ public resumeToken: (Uint8Array|string); /** ExecuteSqlRequest queryMode. */ public queryMode: (google.spanner.v1.ExecuteSqlRequest.QueryMode|keyof typeof google.spanner.v1.ExecuteSqlRequest.QueryMode); /** ExecuteSqlRequest partitionToken. */ public partitionToken: (Uint8Array|string); /** ExecuteSqlRequest seqno. */ public seqno: (number|Long|string); /** ExecuteSqlRequest queryOptions. */ public queryOptions?: (google.spanner.v1.ExecuteSqlRequest.IQueryOptions|null); /** * Creates a new ExecuteSqlRequest instance using the specified properties. * @param [properties] Properties to set * @returns ExecuteSqlRequest instance */ public static create(properties?: google.spanner.v1.IExecuteSqlRequest): google.spanner.v1.ExecuteSqlRequest; /** * Encodes the specified ExecuteSqlRequest message. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.verify|verify} messages. * @param message ExecuteSqlRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IExecuteSqlRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExecuteSqlRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.verify|verify} messages. * @param message ExecuteSqlRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IExecuteSqlRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExecuteSqlRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExecuteSqlRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ExecuteSqlRequest; /** * Decodes an ExecuteSqlRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExecuteSqlRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ExecuteSqlRequest; /** * Verifies an ExecuteSqlRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExecuteSqlRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExecuteSqlRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ExecuteSqlRequest; /** * Creates a plain object from an ExecuteSqlRequest message. Also converts values to other types if specified. * @param message ExecuteSqlRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ExecuteSqlRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExecuteSqlRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace ExecuteSqlRequest { /** Properties of a QueryOptions. */ interface IQueryOptions { /** QueryOptions optimizerVersion */ optimizerVersion?: (string|null); } /** Represents a QueryOptions. */ class QueryOptions implements IQueryOptions { /** * Constructs a new QueryOptions. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.ExecuteSqlRequest.IQueryOptions); /** QueryOptions optimizerVersion. */ public optimizerVersion: string; /** * Creates a new QueryOptions instance using the specified properties. * @param [properties] Properties to set * @returns QueryOptions instance */ public static create(properties?: google.spanner.v1.ExecuteSqlRequest.IQueryOptions): google.spanner.v1.ExecuteSqlRequest.QueryOptions; /** * Encodes the specified QueryOptions message. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.QueryOptions.verify|verify} messages. * @param message QueryOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.ExecuteSqlRequest.IQueryOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified QueryOptions message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteSqlRequest.QueryOptions.verify|verify} messages. * @param message QueryOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.ExecuteSqlRequest.IQueryOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a QueryOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns QueryOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ExecuteSqlRequest.QueryOptions; /** * Decodes a QueryOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns QueryOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ExecuteSqlRequest.QueryOptions; /** * Verifies a QueryOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a QueryOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns QueryOptions */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ExecuteSqlRequest.QueryOptions; /** * Creates a plain object from a QueryOptions message. Also converts values to other types if specified. * @param message QueryOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ExecuteSqlRequest.QueryOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this QueryOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** QueryMode enum. */ enum QueryMode { NORMAL = 0, PLAN = 1, PROFILE = 2 } } /** Properties of an ExecuteBatchDmlRequest. */ interface IExecuteBatchDmlRequest { /** ExecuteBatchDmlRequest session */ session?: (string|null); /** ExecuteBatchDmlRequest transaction */ transaction?: (google.spanner.v1.ITransactionSelector|null); /** ExecuteBatchDmlRequest statements */ statements?: (google.spanner.v1.ExecuteBatchDmlRequest.IStatement[]|null); /** ExecuteBatchDmlRequest seqno */ seqno?: (number|Long|string|null); } /** Represents an ExecuteBatchDmlRequest. */ class ExecuteBatchDmlRequest implements IExecuteBatchDmlRequest { /** * Constructs a new ExecuteBatchDmlRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IExecuteBatchDmlRequest); /** ExecuteBatchDmlRequest session. */ public session: string; /** ExecuteBatchDmlRequest transaction. */ public transaction?: (google.spanner.v1.ITransactionSelector|null); /** ExecuteBatchDmlRequest statements. */ public statements: google.spanner.v1.ExecuteBatchDmlRequest.IStatement[]; /** ExecuteBatchDmlRequest seqno. */ public seqno: (number|Long|string); /** * Creates a new ExecuteBatchDmlRequest instance using the specified properties. * @param [properties] Properties to set * @returns ExecuteBatchDmlRequest instance */ public static create(properties?: google.spanner.v1.IExecuteBatchDmlRequest): google.spanner.v1.ExecuteBatchDmlRequest; /** * Encodes the specified ExecuteBatchDmlRequest message. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.verify|verify} messages. * @param message ExecuteBatchDmlRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IExecuteBatchDmlRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExecuteBatchDmlRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.verify|verify} messages. * @param message ExecuteBatchDmlRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IExecuteBatchDmlRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExecuteBatchDmlRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExecuteBatchDmlRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ExecuteBatchDmlRequest; /** * Decodes an ExecuteBatchDmlRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExecuteBatchDmlRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ExecuteBatchDmlRequest; /** * Verifies an ExecuteBatchDmlRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExecuteBatchDmlRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExecuteBatchDmlRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ExecuteBatchDmlRequest; /** * Creates a plain object from an ExecuteBatchDmlRequest message. Also converts values to other types if specified. * @param message ExecuteBatchDmlRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ExecuteBatchDmlRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExecuteBatchDmlRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace ExecuteBatchDmlRequest { /** Properties of a Statement. */ interface IStatement { /** Statement sql */ sql?: (string|null); /** Statement params */ params?: (google.protobuf.IStruct|null); /** Statement paramTypes */ paramTypes?: ({ [k: string]: google.spanner.v1.IType }|null); } /** Represents a Statement. */ class Statement implements IStatement { /** * Constructs a new Statement. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.ExecuteBatchDmlRequest.IStatement); /** Statement sql. */ public sql: string; /** Statement params. */ public params?: (google.protobuf.IStruct|null); /** Statement paramTypes. */ public paramTypes: { [k: string]: google.spanner.v1.IType }; /** * Creates a new Statement instance using the specified properties. * @param [properties] Properties to set * @returns Statement instance */ public static create(properties?: google.spanner.v1.ExecuteBatchDmlRequest.IStatement): google.spanner.v1.ExecuteBatchDmlRequest.Statement; /** * Encodes the specified Statement message. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.Statement.verify|verify} messages. * @param message Statement message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.ExecuteBatchDmlRequest.IStatement, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Statement message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlRequest.Statement.verify|verify} messages. * @param message Statement message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.ExecuteBatchDmlRequest.IStatement, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Statement message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Statement * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ExecuteBatchDmlRequest.Statement; /** * Decodes a Statement message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Statement * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ExecuteBatchDmlRequest.Statement; /** * Verifies a Statement message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Statement message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Statement */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ExecuteBatchDmlRequest.Statement; /** * Creates a plain object from a Statement message. Also converts values to other types if specified. * @param message Statement * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ExecuteBatchDmlRequest.Statement, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Statement to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of an ExecuteBatchDmlResponse. */ interface IExecuteBatchDmlResponse { /** ExecuteBatchDmlResponse resultSets */ resultSets?: (google.spanner.v1.IResultSet[]|null); /** ExecuteBatchDmlResponse status */ status?: (google.rpc.IStatus|null); } /** Represents an ExecuteBatchDmlResponse. */ class ExecuteBatchDmlResponse implements IExecuteBatchDmlResponse { /** * Constructs a new ExecuteBatchDmlResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IExecuteBatchDmlResponse); /** ExecuteBatchDmlResponse resultSets. */ public resultSets: google.spanner.v1.IResultSet[]; /** ExecuteBatchDmlResponse status. */ public status?: (google.rpc.IStatus|null); /** * Creates a new ExecuteBatchDmlResponse instance using the specified properties. * @param [properties] Properties to set * @returns ExecuteBatchDmlResponse instance */ public static create(properties?: google.spanner.v1.IExecuteBatchDmlResponse): google.spanner.v1.ExecuteBatchDmlResponse; /** * Encodes the specified ExecuteBatchDmlResponse message. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlResponse.verify|verify} messages. * @param message ExecuteBatchDmlResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IExecuteBatchDmlResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ExecuteBatchDmlResponse message, length delimited. Does not implicitly {@link google.spanner.v1.ExecuteBatchDmlResponse.verify|verify} messages. * @param message ExecuteBatchDmlResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IExecuteBatchDmlResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an ExecuteBatchDmlResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ExecuteBatchDmlResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ExecuteBatchDmlResponse; /** * Decodes an ExecuteBatchDmlResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ExecuteBatchDmlResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ExecuteBatchDmlResponse; /** * Verifies an ExecuteBatchDmlResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an ExecuteBatchDmlResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ExecuteBatchDmlResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ExecuteBatchDmlResponse; /** * Creates a plain object from an ExecuteBatchDmlResponse message. Also converts values to other types if specified. * @param message ExecuteBatchDmlResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ExecuteBatchDmlResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ExecuteBatchDmlResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PartitionOptions. */ interface IPartitionOptions { /** PartitionOptions partitionSizeBytes */ partitionSizeBytes?: (number|Long|string|null); /** PartitionOptions maxPartitions */ maxPartitions?: (number|Long|string|null); } /** Represents a PartitionOptions. */ class PartitionOptions implements IPartitionOptions { /** * Constructs a new PartitionOptions. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IPartitionOptions); /** PartitionOptions partitionSizeBytes. */ public partitionSizeBytes: (number|Long|string); /** PartitionOptions maxPartitions. */ public maxPartitions: (number|Long|string); /** * Creates a new PartitionOptions instance using the specified properties. * @param [properties] Properties to set * @returns PartitionOptions instance */ public static create(properties?: google.spanner.v1.IPartitionOptions): google.spanner.v1.PartitionOptions; /** * Encodes the specified PartitionOptions message. Does not implicitly {@link google.spanner.v1.PartitionOptions.verify|verify} messages. * @param message PartitionOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IPartitionOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PartitionOptions message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionOptions.verify|verify} messages. * @param message PartitionOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IPartitionOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PartitionOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PartitionOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PartitionOptions; /** * Decodes a PartitionOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PartitionOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PartitionOptions; /** * Verifies a PartitionOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PartitionOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PartitionOptions */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.PartitionOptions; /** * Creates a plain object from a PartitionOptions message. Also converts values to other types if specified. * @param message PartitionOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.PartitionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PartitionOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PartitionQueryRequest. */ interface IPartitionQueryRequest { /** PartitionQueryRequest session */ session?: (string|null); /** PartitionQueryRequest transaction */ transaction?: (google.spanner.v1.ITransactionSelector|null); /** PartitionQueryRequest sql */ sql?: (string|null); /** PartitionQueryRequest params */ params?: (google.protobuf.IStruct|null); /** PartitionQueryRequest paramTypes */ paramTypes?: ({ [k: string]: google.spanner.v1.IType }|null); /** PartitionQueryRequest partitionOptions */ partitionOptions?: (google.spanner.v1.IPartitionOptions|null); } /** Represents a PartitionQueryRequest. */ class PartitionQueryRequest implements IPartitionQueryRequest { /** * Constructs a new PartitionQueryRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IPartitionQueryRequest); /** PartitionQueryRequest session. */ public session: string; /** PartitionQueryRequest transaction. */ public transaction?: (google.spanner.v1.ITransactionSelector|null); /** PartitionQueryRequest sql. */ public sql: string; /** PartitionQueryRequest params. */ public params?: (google.protobuf.IStruct|null); /** PartitionQueryRequest paramTypes. */ public paramTypes: { [k: string]: google.spanner.v1.IType }; /** PartitionQueryRequest partitionOptions. */ public partitionOptions?: (google.spanner.v1.IPartitionOptions|null); /** * Creates a new PartitionQueryRequest instance using the specified properties. * @param [properties] Properties to set * @returns PartitionQueryRequest instance */ public static create(properties?: google.spanner.v1.IPartitionQueryRequest): google.spanner.v1.PartitionQueryRequest; /** * Encodes the specified PartitionQueryRequest message. Does not implicitly {@link google.spanner.v1.PartitionQueryRequest.verify|verify} messages. * @param message PartitionQueryRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IPartitionQueryRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PartitionQueryRequest message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionQueryRequest.verify|verify} messages. * @param message PartitionQueryRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IPartitionQueryRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PartitionQueryRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PartitionQueryRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PartitionQueryRequest; /** * Decodes a PartitionQueryRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PartitionQueryRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PartitionQueryRequest; /** * Verifies a PartitionQueryRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PartitionQueryRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PartitionQueryRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.PartitionQueryRequest; /** * Creates a plain object from a PartitionQueryRequest message. Also converts values to other types if specified. * @param message PartitionQueryRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.PartitionQueryRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PartitionQueryRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PartitionReadRequest. */ interface IPartitionReadRequest { /** PartitionReadRequest session */ session?: (string|null); /** PartitionReadRequest transaction */ transaction?: (google.spanner.v1.ITransactionSelector|null); /** PartitionReadRequest table */ table?: (string|null); /** PartitionReadRequest index */ index?: (string|null); /** PartitionReadRequest columns */ columns?: (string[]|null); /** PartitionReadRequest keySet */ keySet?: (google.spanner.v1.IKeySet|null); /** PartitionReadRequest partitionOptions */ partitionOptions?: (google.spanner.v1.IPartitionOptions|null); } /** Represents a PartitionReadRequest. */ class PartitionReadRequest implements IPartitionReadRequest { /** * Constructs a new PartitionReadRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IPartitionReadRequest); /** PartitionReadRequest session. */ public session: string; /** PartitionReadRequest transaction. */ public transaction?: (google.spanner.v1.ITransactionSelector|null); /** PartitionReadRequest table. */ public table: string; /** PartitionReadRequest index. */ public index: string; /** PartitionReadRequest columns. */ public columns: string[]; /** PartitionReadRequest keySet. */ public keySet?: (google.spanner.v1.IKeySet|null); /** PartitionReadRequest partitionOptions. */ public partitionOptions?: (google.spanner.v1.IPartitionOptions|null); /** * Creates a new PartitionReadRequest instance using the specified properties. * @param [properties] Properties to set * @returns PartitionReadRequest instance */ public static create(properties?: google.spanner.v1.IPartitionReadRequest): google.spanner.v1.PartitionReadRequest; /** * Encodes the specified PartitionReadRequest message. Does not implicitly {@link google.spanner.v1.PartitionReadRequest.verify|verify} messages. * @param message PartitionReadRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IPartitionReadRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PartitionReadRequest message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionReadRequest.verify|verify} messages. * @param message PartitionReadRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IPartitionReadRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PartitionReadRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PartitionReadRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PartitionReadRequest; /** * Decodes a PartitionReadRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PartitionReadRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PartitionReadRequest; /** * Verifies a PartitionReadRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PartitionReadRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PartitionReadRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.PartitionReadRequest; /** * Creates a plain object from a PartitionReadRequest message. Also converts values to other types if specified. * @param message PartitionReadRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.PartitionReadRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PartitionReadRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Partition. */ interface IPartition { /** Partition partitionToken */ partitionToken?: (Uint8Array|string|null); } /** Represents a Partition. */ class Partition implements IPartition { /** * Constructs a new Partition. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IPartition); /** Partition partitionToken. */ public partitionToken: (Uint8Array|string); /** * Creates a new Partition instance using the specified properties. * @param [properties] Properties to set * @returns Partition instance */ public static create(properties?: google.spanner.v1.IPartition): google.spanner.v1.Partition; /** * Encodes the specified Partition message. Does not implicitly {@link google.spanner.v1.Partition.verify|verify} messages. * @param message Partition message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IPartition, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Partition message, length delimited. Does not implicitly {@link google.spanner.v1.Partition.verify|verify} messages. * @param message Partition message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IPartition, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Partition message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Partition * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Partition; /** * Decodes a Partition message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Partition * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Partition; /** * Verifies a Partition message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Partition message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Partition */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.Partition; /** * Creates a plain object from a Partition message. Also converts values to other types if specified. * @param message Partition * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.Partition, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Partition to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PartitionResponse. */ interface IPartitionResponse { /** PartitionResponse partitions */ partitions?: (google.spanner.v1.IPartition[]|null); /** PartitionResponse transaction */ transaction?: (google.spanner.v1.ITransaction|null); } /** Represents a PartitionResponse. */ class PartitionResponse implements IPartitionResponse { /** * Constructs a new PartitionResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IPartitionResponse); /** PartitionResponse partitions. */ public partitions: google.spanner.v1.IPartition[]; /** PartitionResponse transaction. */ public transaction?: (google.spanner.v1.ITransaction|null); /** * Creates a new PartitionResponse instance using the specified properties. * @param [properties] Properties to set * @returns PartitionResponse instance */ public static create(properties?: google.spanner.v1.IPartitionResponse): google.spanner.v1.PartitionResponse; /** * Encodes the specified PartitionResponse message. Does not implicitly {@link google.spanner.v1.PartitionResponse.verify|verify} messages. * @param message PartitionResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IPartitionResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PartitionResponse message, length delimited. Does not implicitly {@link google.spanner.v1.PartitionResponse.verify|verify} messages. * @param message PartitionResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IPartitionResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PartitionResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PartitionResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PartitionResponse; /** * Decodes a PartitionResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PartitionResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PartitionResponse; /** * Verifies a PartitionResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PartitionResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PartitionResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.PartitionResponse; /** * Creates a plain object from a PartitionResponse message. Also converts values to other types if specified. * @param message PartitionResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.PartitionResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PartitionResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ReadRequest. */ interface IReadRequest { /** ReadRequest session */ session?: (string|null); /** ReadRequest transaction */ transaction?: (google.spanner.v1.ITransactionSelector|null); /** ReadRequest table */ table?: (string|null); /** ReadRequest index */ index?: (string|null); /** ReadRequest columns */ columns?: (string[]|null); /** ReadRequest keySet */ keySet?: (google.spanner.v1.IKeySet|null); /** ReadRequest limit */ limit?: (number|Long|string|null); /** ReadRequest resumeToken */ resumeToken?: (Uint8Array|string|null); /** ReadRequest partitionToken */ partitionToken?: (Uint8Array|string|null); } /** Represents a ReadRequest. */ class ReadRequest implements IReadRequest { /** * Constructs a new ReadRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IReadRequest); /** ReadRequest session. */ public session: string; /** ReadRequest transaction. */ public transaction?: (google.spanner.v1.ITransactionSelector|null); /** ReadRequest table. */ public table: string; /** ReadRequest index. */ public index: string; /** ReadRequest columns. */ public columns: string[]; /** ReadRequest keySet. */ public keySet?: (google.spanner.v1.IKeySet|null); /** ReadRequest limit. */ public limit: (number|Long|string); /** ReadRequest resumeToken. */ public resumeToken: (Uint8Array|string); /** ReadRequest partitionToken. */ public partitionToken: (Uint8Array|string); /** * Creates a new ReadRequest instance using the specified properties. * @param [properties] Properties to set * @returns ReadRequest instance */ public static create(properties?: google.spanner.v1.IReadRequest): google.spanner.v1.ReadRequest; /** * Encodes the specified ReadRequest message. Does not implicitly {@link google.spanner.v1.ReadRequest.verify|verify} messages. * @param message ReadRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IReadRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ReadRequest message, length delimited. Does not implicitly {@link google.spanner.v1.ReadRequest.verify|verify} messages. * @param message ReadRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IReadRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ReadRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ReadRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ReadRequest; /** * Decodes a ReadRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ReadRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ReadRequest; /** * Verifies a ReadRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ReadRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ReadRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ReadRequest; /** * Creates a plain object from a ReadRequest message. Also converts values to other types if specified. * @param message ReadRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ReadRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ReadRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BeginTransactionRequest. */ interface IBeginTransactionRequest { /** BeginTransactionRequest session */ session?: (string|null); /** BeginTransactionRequest options */ options?: (google.spanner.v1.ITransactionOptions|null); } /** Represents a BeginTransactionRequest. */ class BeginTransactionRequest implements IBeginTransactionRequest { /** * Constructs a new BeginTransactionRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IBeginTransactionRequest); /** BeginTransactionRequest session. */ public session: string; /** BeginTransactionRequest options. */ public options?: (google.spanner.v1.ITransactionOptions|null); /** * Creates a new BeginTransactionRequest instance using the specified properties. * @param [properties] Properties to set * @returns BeginTransactionRequest instance */ public static create(properties?: google.spanner.v1.IBeginTransactionRequest): google.spanner.v1.BeginTransactionRequest; /** * Encodes the specified BeginTransactionRequest message. Does not implicitly {@link google.spanner.v1.BeginTransactionRequest.verify|verify} messages. * @param message BeginTransactionRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IBeginTransactionRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BeginTransactionRequest message, length delimited. Does not implicitly {@link google.spanner.v1.BeginTransactionRequest.verify|verify} messages. * @param message BeginTransactionRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IBeginTransactionRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BeginTransactionRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BeginTransactionRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.BeginTransactionRequest; /** * Decodes a BeginTransactionRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BeginTransactionRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.BeginTransactionRequest; /** * Verifies a BeginTransactionRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BeginTransactionRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BeginTransactionRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.BeginTransactionRequest; /** * Creates a plain object from a BeginTransactionRequest message. Also converts values to other types if specified. * @param message BeginTransactionRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.BeginTransactionRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BeginTransactionRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CommitRequest. */ interface ICommitRequest { /** CommitRequest session */ session?: (string|null); /** CommitRequest transactionId */ transactionId?: (Uint8Array|string|null); /** CommitRequest singleUseTransaction */ singleUseTransaction?: (google.spanner.v1.ITransactionOptions|null); /** CommitRequest mutations */ mutations?: (google.spanner.v1.IMutation[]|null); } /** Represents a CommitRequest. */ class CommitRequest implements ICommitRequest { /** * Constructs a new CommitRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.ICommitRequest); /** CommitRequest session. */ public session: string; /** CommitRequest transactionId. */ public transactionId: (Uint8Array|string); /** CommitRequest singleUseTransaction. */ public singleUseTransaction?: (google.spanner.v1.ITransactionOptions|null); /** CommitRequest mutations. */ public mutations: google.spanner.v1.IMutation[]; /** CommitRequest transaction. */ public transaction?: ("transactionId"|"singleUseTransaction"); /** * Creates a new CommitRequest instance using the specified properties. * @param [properties] Properties to set * @returns CommitRequest instance */ public static create(properties?: google.spanner.v1.ICommitRequest): google.spanner.v1.CommitRequest; /** * Encodes the specified CommitRequest message. Does not implicitly {@link google.spanner.v1.CommitRequest.verify|verify} messages. * @param message CommitRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.ICommitRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CommitRequest message, length delimited. Does not implicitly {@link google.spanner.v1.CommitRequest.verify|verify} messages. * @param message CommitRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.ICommitRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CommitRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CommitRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.CommitRequest; /** * Decodes a CommitRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CommitRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.CommitRequest; /** * Verifies a CommitRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CommitRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CommitRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.CommitRequest; /** * Creates a plain object from a CommitRequest message. Also converts values to other types if specified. * @param message CommitRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.CommitRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CommitRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CommitResponse. */ interface ICommitResponse { /** CommitResponse commitTimestamp */ commitTimestamp?: (google.protobuf.ITimestamp|null); } /** Represents a CommitResponse. */ class CommitResponse implements ICommitResponse { /** * Constructs a new CommitResponse. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.ICommitResponse); /** CommitResponse commitTimestamp. */ public commitTimestamp?: (google.protobuf.ITimestamp|null); /** * Creates a new CommitResponse instance using the specified properties. * @param [properties] Properties to set * @returns CommitResponse instance */ public static create(properties?: google.spanner.v1.ICommitResponse): google.spanner.v1.CommitResponse; /** * Encodes the specified CommitResponse message. Does not implicitly {@link google.spanner.v1.CommitResponse.verify|verify} messages. * @param message CommitResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.ICommitResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CommitResponse message, length delimited. Does not implicitly {@link google.spanner.v1.CommitResponse.verify|verify} messages. * @param message CommitResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.ICommitResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CommitResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CommitResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.CommitResponse; /** * Decodes a CommitResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CommitResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.CommitResponse; /** * Verifies a CommitResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CommitResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CommitResponse */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.CommitResponse; /** * Creates a plain object from a CommitResponse message. Also converts values to other types if specified. * @param message CommitResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.CommitResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CommitResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a RollbackRequest. */ interface IRollbackRequest { /** RollbackRequest session */ session?: (string|null); /** RollbackRequest transactionId */ transactionId?: (Uint8Array|string|null); } /** Represents a RollbackRequest. */ class RollbackRequest implements IRollbackRequest { /** * Constructs a new RollbackRequest. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IRollbackRequest); /** RollbackRequest session. */ public session: string; /** RollbackRequest transactionId. */ public transactionId: (Uint8Array|string); /** * Creates a new RollbackRequest instance using the specified properties. * @param [properties] Properties to set * @returns RollbackRequest instance */ public static create(properties?: google.spanner.v1.IRollbackRequest): google.spanner.v1.RollbackRequest; /** * Encodes the specified RollbackRequest message. Does not implicitly {@link google.spanner.v1.RollbackRequest.verify|verify} messages. * @param message RollbackRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IRollbackRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified RollbackRequest message, length delimited. Does not implicitly {@link google.spanner.v1.RollbackRequest.verify|verify} messages. * @param message RollbackRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IRollbackRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a RollbackRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns RollbackRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.RollbackRequest; /** * Decodes a RollbackRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns RollbackRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.RollbackRequest; /** * Verifies a RollbackRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a RollbackRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns RollbackRequest */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.RollbackRequest; /** * Creates a plain object from a RollbackRequest message. Also converts values to other types if specified. * @param message RollbackRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.RollbackRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this RollbackRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a KeyRange. */ interface IKeyRange { /** KeyRange startClosed */ startClosed?: (google.protobuf.IListValue|null); /** KeyRange startOpen */ startOpen?: (google.protobuf.IListValue|null); /** KeyRange endClosed */ endClosed?: (google.protobuf.IListValue|null); /** KeyRange endOpen */ endOpen?: (google.protobuf.IListValue|null); } /** Represents a KeyRange. */ class KeyRange implements IKeyRange { /** * Constructs a new KeyRange. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IKeyRange); /** KeyRange startClosed. */ public startClosed?: (google.protobuf.IListValue|null); /** KeyRange startOpen. */ public startOpen?: (google.protobuf.IListValue|null); /** KeyRange endClosed. */ public endClosed?: (google.protobuf.IListValue|null); /** KeyRange endOpen. */ public endOpen?: (google.protobuf.IListValue|null); /** KeyRange startKeyType. */ public startKeyType?: ("startClosed"|"startOpen"); /** KeyRange endKeyType. */ public endKeyType?: ("endClosed"|"endOpen"); /** * Creates a new KeyRange instance using the specified properties. * @param [properties] Properties to set * @returns KeyRange instance */ public static create(properties?: google.spanner.v1.IKeyRange): google.spanner.v1.KeyRange; /** * Encodes the specified KeyRange message. Does not implicitly {@link google.spanner.v1.KeyRange.verify|verify} messages. * @param message KeyRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IKeyRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified KeyRange message, length delimited. Does not implicitly {@link google.spanner.v1.KeyRange.verify|verify} messages. * @param message KeyRange message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IKeyRange, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a KeyRange message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns KeyRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.KeyRange; /** * Decodes a KeyRange message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns KeyRange * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.KeyRange; /** * Verifies a KeyRange message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a KeyRange message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns KeyRange */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.KeyRange; /** * Creates a plain object from a KeyRange message. Also converts values to other types if specified. * @param message KeyRange * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.KeyRange, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this KeyRange to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a KeySet. */ interface IKeySet { /** KeySet keys */ keys?: (google.protobuf.IListValue[]|null); /** KeySet ranges */ ranges?: (google.spanner.v1.IKeyRange[]|null); /** KeySet all */ all?: (boolean|null); } /** Represents a KeySet. */ class KeySet implements IKeySet { /** * Constructs a new KeySet. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IKeySet); /** KeySet keys. */ public keys: google.protobuf.IListValue[]; /** KeySet ranges. */ public ranges: google.spanner.v1.IKeyRange[]; /** KeySet all. */ public all: boolean; /** * Creates a new KeySet instance using the specified properties. * @param [properties] Properties to set * @returns KeySet instance */ public static create(properties?: google.spanner.v1.IKeySet): google.spanner.v1.KeySet; /** * Encodes the specified KeySet message. Does not implicitly {@link google.spanner.v1.KeySet.verify|verify} messages. * @param message KeySet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IKeySet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified KeySet message, length delimited. Does not implicitly {@link google.spanner.v1.KeySet.verify|verify} messages. * @param message KeySet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IKeySet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a KeySet message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns KeySet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.KeySet; /** * Decodes a KeySet message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns KeySet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.KeySet; /** * Verifies a KeySet message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a KeySet message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns KeySet */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.KeySet; /** * Creates a plain object from a KeySet message. Also converts values to other types if specified. * @param message KeySet * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.KeySet, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this KeySet to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Mutation. */ interface IMutation { /** Mutation insert */ insert?: (google.spanner.v1.Mutation.IWrite|null); /** Mutation update */ update?: (google.spanner.v1.Mutation.IWrite|null); /** Mutation insertOrUpdate */ insertOrUpdate?: (google.spanner.v1.Mutation.IWrite|null); /** Mutation replace */ replace?: (google.spanner.v1.Mutation.IWrite|null); /** Mutation delete */ "delete"?: (google.spanner.v1.Mutation.IDelete|null); } /** Represents a Mutation. */ class Mutation implements IMutation { /** * Constructs a new Mutation. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IMutation); /** Mutation insert. */ public insert?: (google.spanner.v1.Mutation.IWrite|null); /** Mutation update. */ public update?: (google.spanner.v1.Mutation.IWrite|null); /** Mutation insertOrUpdate. */ public insertOrUpdate?: (google.spanner.v1.Mutation.IWrite|null); /** Mutation replace. */ public replace?: (google.spanner.v1.Mutation.IWrite|null); /** Mutation delete. */ public delete?: (google.spanner.v1.Mutation.IDelete|null); /** Mutation operation. */ public operation?: ("insert"|"update"|"insertOrUpdate"|"replace"|"delete"); /** * Creates a new Mutation instance using the specified properties. * @param [properties] Properties to set * @returns Mutation instance */ public static create(properties?: google.spanner.v1.IMutation): google.spanner.v1.Mutation; /** * Encodes the specified Mutation message. Does not implicitly {@link google.spanner.v1.Mutation.verify|verify} messages. * @param message Mutation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IMutation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Mutation message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.verify|verify} messages. * @param message Mutation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IMutation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Mutation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Mutation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Mutation; /** * Decodes a Mutation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Mutation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Mutation; /** * Verifies a Mutation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Mutation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Mutation */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.Mutation; /** * Creates a plain object from a Mutation message. Also converts values to other types if specified. * @param message Mutation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.Mutation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Mutation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Mutation { /** Properties of a Write. */ interface IWrite { /** Write table */ table?: (string|null); /** Write columns */ columns?: (string[]|null); /** Write values */ values?: (google.protobuf.IListValue[]|null); } /** Represents a Write. */ class Write implements IWrite { /** * Constructs a new Write. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.Mutation.IWrite); /** Write table. */ public table: string; /** Write columns. */ public columns: string[]; /** Write values. */ public values: google.protobuf.IListValue[]; /** * Creates a new Write instance using the specified properties. * @param [properties] Properties to set * @returns Write instance */ public static create(properties?: google.spanner.v1.Mutation.IWrite): google.spanner.v1.Mutation.Write; /** * Encodes the specified Write message. Does not implicitly {@link google.spanner.v1.Mutation.Write.verify|verify} messages. * @param message Write message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.Mutation.IWrite, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Write message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.Write.verify|verify} messages. * @param message Write message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.Mutation.IWrite, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Write message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Write * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Mutation.Write; /** * Decodes a Write message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Write * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Mutation.Write; /** * Verifies a Write message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Write message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Write */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.Mutation.Write; /** * Creates a plain object from a Write message. Also converts values to other types if specified. * @param message Write * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.Mutation.Write, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Write to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Delete. */ interface IDelete { /** Delete table */ table?: (string|null); /** Delete keySet */ keySet?: (google.spanner.v1.IKeySet|null); } /** Represents a Delete. */ class Delete implements IDelete { /** * Constructs a new Delete. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.Mutation.IDelete); /** Delete table. */ public table: string; /** Delete keySet. */ public keySet?: (google.spanner.v1.IKeySet|null); /** * Creates a new Delete instance using the specified properties. * @param [properties] Properties to set * @returns Delete instance */ public static create(properties?: google.spanner.v1.Mutation.IDelete): google.spanner.v1.Mutation.Delete; /** * Encodes the specified Delete message. Does not implicitly {@link google.spanner.v1.Mutation.Delete.verify|verify} messages. * @param message Delete message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.Mutation.IDelete, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Delete message, length delimited. Does not implicitly {@link google.spanner.v1.Mutation.Delete.verify|verify} messages. * @param message Delete message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.Mutation.IDelete, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Delete message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Delete * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Mutation.Delete; /** * Decodes a Delete message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Delete * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Mutation.Delete; /** * Verifies a Delete message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Delete message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Delete */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.Mutation.Delete; /** * Creates a plain object from a Delete message. Also converts values to other types if specified. * @param message Delete * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.Mutation.Delete, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Delete to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a ResultSet. */ interface IResultSet { /** ResultSet metadata */ metadata?: (google.spanner.v1.IResultSetMetadata|null); /** ResultSet rows */ rows?: (google.protobuf.IListValue[]|null); /** ResultSet stats */ stats?: (google.spanner.v1.IResultSetStats|null); } /** Represents a ResultSet. */ class ResultSet implements IResultSet { /** * Constructs a new ResultSet. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IResultSet); /** ResultSet metadata. */ public metadata?: (google.spanner.v1.IResultSetMetadata|null); /** ResultSet rows. */ public rows: google.protobuf.IListValue[]; /** ResultSet stats. */ public stats?: (google.spanner.v1.IResultSetStats|null); /** * Creates a new ResultSet instance using the specified properties. * @param [properties] Properties to set * @returns ResultSet instance */ public static create(properties?: google.spanner.v1.IResultSet): google.spanner.v1.ResultSet; /** * Encodes the specified ResultSet message. Does not implicitly {@link google.spanner.v1.ResultSet.verify|verify} messages. * @param message ResultSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IResultSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ResultSet message, length delimited. Does not implicitly {@link google.spanner.v1.ResultSet.verify|verify} messages. * @param message ResultSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IResultSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ResultSet message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ResultSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ResultSet; /** * Decodes a ResultSet message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ResultSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ResultSet; /** * Verifies a ResultSet message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ResultSet message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ResultSet */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ResultSet; /** * Creates a plain object from a ResultSet message. Also converts values to other types if specified. * @param message ResultSet * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ResultSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ResultSet to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PartialResultSet. */ interface IPartialResultSet { /** PartialResultSet metadata */ metadata?: (google.spanner.v1.IResultSetMetadata|null); /** PartialResultSet values */ values?: (google.protobuf.IValue[]|null); /** PartialResultSet chunkedValue */ chunkedValue?: (boolean|null); /** PartialResultSet resumeToken */ resumeToken?: (Uint8Array|string|null); /** PartialResultSet stats */ stats?: (google.spanner.v1.IResultSetStats|null); } /** Represents a PartialResultSet. */ class
implements IPartialResultSet { /** * Constructs a new PartialResultSet. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IPartialResultSet); /** PartialResultSet metadata. */ public metadata?: (google.spanner.v1.IResultSetMetadata|null); /** PartialResultSet values. */ public values: google.protobuf.IValue[]; /** PartialResultSet chunkedValue. */ public chunkedValue: boolean; /** PartialResultSet resumeToken. */ public resumeToken: (Uint8Array|string); /** PartialResultSet stats. */ public stats?: (google.spanner.v1.IResultSetStats|null); /** * Creates a new PartialResultSet instance using the specified properties. * @param [properties] Properties to set * @returns PartialResultSet instance */ public static create(properties?: google.spanner.v1.IPartialResultSet): google.spanner.v1.PartialResultSet; /** * Encodes the specified PartialResultSet message. Does not implicitly {@link google.spanner.v1.PartialResultSet.verify|verify} messages. * @param message PartialResultSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IPartialResultSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PartialResultSet message, length delimited. Does not implicitly {@link google.spanner.v1.PartialResultSet.verify|verify} messages. * @param message PartialResultSet message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IPartialResultSet, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PartialResultSet message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PartialResultSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PartialResultSet; /** * Decodes a PartialResultSet message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PartialResultSet * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PartialResultSet; /** * Verifies a PartialResultSet message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PartialResultSet message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PartialResultSet */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.PartialResultSet; /** * Creates a plain object from a PartialResultSet message. Also converts values to other types if specified. * @param message PartialResultSet * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.PartialResultSet, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PartialResultSet to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ResultSetMetadata. */ interface IResultSetMetadata { /** ResultSetMetadata rowType */ rowType?: (google.spanner.v1.IStructType|null); /** ResultSetMetadata transaction */ transaction?: (google.spanner.v1.ITransaction|null); } /** Represents a ResultSetMetadata. */ class ResultSetMetadata implements IResultSetMetadata { /** * Constructs a new ResultSetMetadata. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IResultSetMetadata); /** ResultSetMetadata rowType. */ public rowType?: (google.spanner.v1.IStructType|null); /** ResultSetMetadata transaction. */ public transaction?: (google.spanner.v1.ITransaction|null); /** * Creates a new ResultSetMetadata instance using the specified properties. * @param [properties] Properties to set * @returns ResultSetMetadata instance */ public static create(properties?: google.spanner.v1.IResultSetMetadata): google.spanner.v1.ResultSetMetadata; /** * Encodes the specified ResultSetMetadata message. Does not implicitly {@link google.spanner.v1.ResultSetMetadata.verify|verify} messages. * @param message ResultSetMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IResultSetMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ResultSetMetadata message, length delimited. Does not implicitly {@link google.spanner.v1.ResultSetMetadata.verify|verify} messages. * @param message ResultSetMetadata message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IResultSetMetadata, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ResultSetMetadata message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ResultSetMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ResultSetMetadata; /** * Decodes a ResultSetMetadata message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ResultSetMetadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ResultSetMetadata; /** * Verifies a ResultSetMetadata message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ResultSetMetadata message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ResultSetMetadata */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ResultSetMetadata; /** * Creates a plain object from a ResultSetMetadata message. Also converts values to other types if specified. * @param message ResultSetMetadata * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ResultSetMetadata, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ResultSetMetadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ResultSetStats. */ interface IResultSetStats { /** ResultSetStats queryPlan */ queryPlan?: (google.spanner.v1.IQueryPlan|null); /** ResultSetStats queryStats */ queryStats?: (google.protobuf.IStruct|null); /** ResultSetStats rowCountExact */ rowCountExact?: (number|Long|string|null); /** ResultSetStats rowCountLowerBound */ rowCountLowerBound?: (number|Long|string|null); } /** Represents a ResultSetStats. */ class ResultSetStats implements IResultSetStats { /** * Constructs a new ResultSetStats. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IResultSetStats); /** ResultSetStats queryPlan. */ public queryPlan?: (google.spanner.v1.IQueryPlan|null); /** ResultSetStats queryStats. */ public queryStats?: (google.protobuf.IStruct|null); /** ResultSetStats rowCountExact. */ public rowCountExact: (number|Long|string); /** ResultSetStats rowCountLowerBound. */ public rowCountLowerBound: (number|Long|string); /** ResultSetStats rowCount. */ public rowCount?: ("rowCountExact"|"rowCountLowerBound"); /** * Creates a new ResultSetStats instance using the specified properties. * @param [properties] Properties to set * @returns ResultSetStats instance */ public static create(properties?: google.spanner.v1.IResultSetStats): google.spanner.v1.ResultSetStats; /** * Encodes the specified ResultSetStats message. Does not implicitly {@link google.spanner.v1.ResultSetStats.verify|verify} messages. * @param message ResultSetStats message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IResultSetStats, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ResultSetStats message, length delimited. Does not implicitly {@link google.spanner.v1.ResultSetStats.verify|verify} messages. * @param message ResultSetStats message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IResultSetStats, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ResultSetStats message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ResultSetStats * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.ResultSetStats; /** * Decodes a ResultSetStats message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ResultSetStats * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.ResultSetStats; /** * Verifies a ResultSetStats message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ResultSetStats message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ResultSetStats */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.ResultSetStats; /** * Creates a plain object from a ResultSetStats message. Also converts values to other types if specified. * @param message ResultSetStats * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.ResultSetStats, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ResultSetStats to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PlanNode. */ interface IPlanNode { /** PlanNode index */ index?: (number|null); /** PlanNode kind */ kind?: (google.spanner.v1.PlanNode.Kind|keyof typeof google.spanner.v1.PlanNode.Kind|null); /** PlanNode displayName */ displayName?: (string|null); /** PlanNode childLinks */ childLinks?: (google.spanner.v1.PlanNode.IChildLink[]|null); /** PlanNode shortRepresentation */ shortRepresentation?: (google.spanner.v1.PlanNode.IShortRepresentation|null); /** PlanNode metadata */ metadata?: (google.protobuf.IStruct|null); /** PlanNode executionStats */ executionStats?: (google.protobuf.IStruct|null); } /** Represents a PlanNode. */ class PlanNode implements IPlanNode { /** * Constructs a new PlanNode. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IPlanNode); /** PlanNode index. */ public index: number; /** PlanNode kind. */ public kind: (google.spanner.v1.PlanNode.Kind|keyof typeof google.spanner.v1.PlanNode.Kind); /** PlanNode displayName. */ public displayName: string; /** PlanNode childLinks. */ public childLinks: google.spanner.v1.PlanNode.IChildLink[]; /** PlanNode shortRepresentation. */ public shortRepresentation?: (google.spanner.v1.PlanNode.IShortRepresentation|null); /** PlanNode metadata. */ public metadata?: (google.protobuf.IStruct|null); /** PlanNode executionStats. */ public executionStats?: (google.protobuf.IStruct|null); /** * Creates a new PlanNode instance using the specified properties. * @param [properties] Properties to set * @returns PlanNode instance */ public static create(properties?: google.spanner.v1.IPlanNode): google.spanner.v1.PlanNode; /** * Encodes the specified PlanNode message. Does not implicitly {@link google.spanner.v1.PlanNode.verify|verify} messages. * @param message PlanNode message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IPlanNode, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PlanNode message, length delimited. Does not implicitly {@link google.spanner.v1.PlanNode.verify|verify} messages. * @param message PlanNode message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IPlanNode, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PlanNode message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PlanNode * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PlanNode; /** * Decodes a PlanNode message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PlanNode * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PlanNode; /** * Verifies a PlanNode message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PlanNode message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PlanNode */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.PlanNode; /** * Creates a plain object from a PlanNode message. Also converts values to other types if specified. * @param message PlanNode * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.PlanNode, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PlanNode to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace PlanNode { /** Properties of a ChildLink. */ interface IChildLink { /** ChildLink childIndex */ childIndex?: (number|null); /** ChildLink type */ type?: (string|null); /** ChildLink variable */ variable?: (string|null); } /** Represents a ChildLink. */ class ChildLink implements IChildLink { /** * Constructs a new ChildLink. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.PlanNode.IChildLink); /** ChildLink childIndex. */ public childIndex: number; /** ChildLink type. */ public type: string; /** ChildLink variable. */ public variable: string; /** * Creates a new ChildLink instance using the specified properties. * @param [properties] Properties to set * @returns ChildLink instance */ public static create(properties?: google.spanner.v1.PlanNode.IChildLink): google.spanner.v1.PlanNode.ChildLink; /** * Encodes the specified ChildLink message. Does not implicitly {@link google.spanner.v1.PlanNode.ChildLink.verify|verify} messages. * @param message ChildLink message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.PlanNode.IChildLink, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ChildLink message, length delimited. Does not implicitly {@link google.spanner.v1.PlanNode.ChildLink.verify|verify} messages. * @param message ChildLink message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.PlanNode.IChildLink, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ChildLink message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ChildLink * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PlanNode.ChildLink; /** * Decodes a ChildLink message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ChildLink * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PlanNode.ChildLink; /** * Verifies a ChildLink message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ChildLink message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ChildLink */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.PlanNode.ChildLink; /** * Creates a plain object from a ChildLink message. Also converts values to other types if specified. * @param message ChildLink * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.PlanNode.ChildLink, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ChildLink to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ShortRepresentation. */ interface IShortRepresentation { /** ShortRepresentation description */ description?: (string|null); /** ShortRepresentation subqueries */ subqueries?: ({ [k: string]: number }|null); } /** Represents a ShortRepresentation. */ class ShortRepresentation implements IShortRepresentation { /** * Constructs a new ShortRepresentation. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.PlanNode.IShortRepresentation); /** ShortRepresentation description. */ public description: string; /** ShortRepresentation subqueries. */ public subqueries: { [k: string]: number }; /** * Creates a new ShortRepresentation instance using the specified properties. * @param [properties] Properties to set * @returns ShortRepresentation instance */ public static create(properties?: google.spanner.v1.PlanNode.IShortRepresentation): google.spanner.v1.PlanNode.ShortRepresentation; /** * Encodes the specified ShortRepresentation message. Does not implicitly {@link google.spanner.v1.PlanNode.ShortRepresentation.verify|verify} messages. * @param message ShortRepresentation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.PlanNode.IShortRepresentation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ShortRepresentation message, length delimited. Does not implicitly {@link google.spanner.v1.PlanNode.ShortRepresentation.verify|verify} messages. * @param message ShortRepresentation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.PlanNode.IShortRepresentation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ShortRepresentation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ShortRepresentation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.PlanNode.ShortRepresentation; /** * Decodes a ShortRepresentation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ShortRepresentation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.PlanNode.ShortRepresentation; /** * Verifies a ShortRepresentation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ShortRepresentation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ShortRepresentation */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.PlanNode.ShortRepresentation; /** * Creates a plain object from a ShortRepresentation message. Also converts values to other types if specified. * @param message ShortRepresentation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.PlanNode.ShortRepresentation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ShortRepresentation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Kind enum. */ enum Kind { KIND_UNSPECIFIED = 0, RELATIONAL = 1, SCALAR = 2 } } /** Properties of a QueryPlan. */ interface IQueryPlan { /** QueryPlan planNodes */ planNodes?: (google.spanner.v1.IPlanNode[]|null); } /** Represents a QueryPlan. */ class QueryPlan implements IQueryPlan { /** * Constructs a new QueryPlan. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IQueryPlan); /** QueryPlan planNodes. */ public planNodes: google.spanner.v1.IPlanNode[]; /** * Creates a new QueryPlan instance using the specified properties. * @param [properties] Properties to set * @returns QueryPlan instance */ public static create(properties?: google.spanner.v1.IQueryPlan): google.spanner.v1.QueryPlan; /** * Encodes the specified QueryPlan message. Does not implicitly {@link google.spanner.v1.QueryPlan.verify|verify} messages. * @param message QueryPlan message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IQueryPlan, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified QueryPlan message, length delimited. Does not implicitly {@link google.spanner.v1.QueryPlan.verify|verify} messages. * @param message QueryPlan message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IQueryPlan, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a QueryPlan message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns QueryPlan * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.QueryPlan; /** * Decodes a QueryPlan message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns QueryPlan * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.QueryPlan; /** * Verifies a QueryPlan message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a QueryPlan message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns QueryPlan */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.QueryPlan; /** * Creates a plain object from a QueryPlan message. Also converts values to other types if specified. * @param message QueryPlan * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.QueryPlan, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this QueryPlan to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a TransactionOptions. */ interface ITransactionOptions { /** TransactionOptions readWrite */ readWrite?: (google.spanner.v1.TransactionOptions.IReadWrite|null); /** TransactionOptions partitionedDml */ partitionedDml?: (google.spanner.v1.TransactionOptions.IPartitionedDml|null); /** TransactionOptions readOnly */ readOnly?: (google.spanner.v1.TransactionOptions.IReadOnly|null); } /** Represents a TransactionOptions. */ class TransactionOptions implements ITransactionOptions { /** * Constructs a new TransactionOptions. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.ITransactionOptions); /** TransactionOptions readWrite. */ public readWrite?: (google.spanner.v1.TransactionOptions.IReadWrite|null); /** TransactionOptions partitionedDml. */ public partitionedDml?: (google.spanner.v1.TransactionOptions.IPartitionedDml|null); /** TransactionOptions readOnly. */ public readOnly?: (google.spanner.v1.TransactionOptions.IReadOnly|null); /** TransactionOptions mode. */ public mode?: ("readWrite"|"partitionedDml"|"readOnly"); /** * Creates a new TransactionOptions instance using the specified properties. * @param [properties] Properties to set * @returns TransactionOptions instance */ public static create(properties?: google.spanner.v1.ITransactionOptions): google.spanner.v1.TransactionOptions; /** * Encodes the specified TransactionOptions message. Does not implicitly {@link google.spanner.v1.TransactionOptions.verify|verify} messages. * @param message TransactionOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.ITransactionOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified TransactionOptions message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.verify|verify} messages. * @param message TransactionOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.ITransactionOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a TransactionOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns TransactionOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.TransactionOptions; /** * Decodes a TransactionOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns TransactionOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.TransactionOptions; /** * Verifies a TransactionOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a TransactionOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns TransactionOptions */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.TransactionOptions; /** * Creates a plain object from a TransactionOptions message. Also converts values to other types if specified. * @param message TransactionOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.TransactionOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this TransactionOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace TransactionOptions { /** Properties of a ReadWrite. */ interface IReadWrite { } /** Represents a ReadWrite. */ class ReadWrite implements IReadWrite { /** * Constructs a new ReadWrite. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.TransactionOptions.IReadWrite); /** * Creates a new ReadWrite instance using the specified properties. * @param [properties] Properties to set * @returns ReadWrite instance */ public static create(properties?: google.spanner.v1.TransactionOptions.IReadWrite): google.spanner.v1.TransactionOptions.ReadWrite; /** * Encodes the specified ReadWrite message. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadWrite.verify|verify} messages. * @param message ReadWrite message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.TransactionOptions.IReadWrite, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ReadWrite message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadWrite.verify|verify} messages. * @param message ReadWrite message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.TransactionOptions.IReadWrite, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ReadWrite message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ReadWrite * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.TransactionOptions.ReadWrite; /** * Decodes a ReadWrite message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ReadWrite * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.TransactionOptions.ReadWrite; /** * Verifies a ReadWrite message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ReadWrite message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ReadWrite */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.TransactionOptions.ReadWrite; /** * Creates a plain object from a ReadWrite message. Also converts values to other types if specified. * @param message ReadWrite * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.TransactionOptions.ReadWrite, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ReadWrite to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PartitionedDml. */ interface IPartitionedDml { } /** Represents a PartitionedDml. */ class PartitionedDml implements IPartitionedDml { /** * Constructs a new PartitionedDml. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.TransactionOptions.IPartitionedDml); /** * Creates a new PartitionedDml instance using the specified properties. * @param [properties] Properties to set * @returns PartitionedDml instance */ public static create(properties?: google.spanner.v1.TransactionOptions.IPartitionedDml): google.spanner.v1.TransactionOptions.PartitionedDml; /** * Encodes the specified PartitionedDml message. Does not implicitly {@link google.spanner.v1.TransactionOptions.PartitionedDml.verify|verify} messages. * @param message PartitionedDml message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.TransactionOptions.IPartitionedDml, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PartitionedDml message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.PartitionedDml.verify|verify} messages. * @param message PartitionedDml message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.TransactionOptions.IPartitionedDml, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PartitionedDml message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PartitionedDml * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.TransactionOptions.PartitionedDml; /** * Decodes a PartitionedDml message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PartitionedDml * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.TransactionOptions.PartitionedDml; /** * Verifies a PartitionedDml message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PartitionedDml message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PartitionedDml */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.TransactionOptions.PartitionedDml; /** * Creates a plain object from a PartitionedDml message. Also converts values to other types if specified. * @param message PartitionedDml * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.TransactionOptions.PartitionedDml, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PartitionedDml to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ReadOnly. */ interface IReadOnly { /** ReadOnly strong */ strong?: (boolean|null); /** ReadOnly minReadTimestamp */ minReadTimestamp?: (google.protobuf.ITimestamp|null); /** ReadOnly maxStaleness */ maxStaleness?: (google.protobuf.IDuration|null); /** ReadOnly readTimestamp */ readTimestamp?: (google.protobuf.ITimestamp|null); /** ReadOnly exactStaleness */ exactStaleness?: (google.protobuf.IDuration|null); /** ReadOnly returnReadTimestamp */ returnReadTimestamp?: (boolean|null); } /** Represents a ReadOnly. */ class ReadOnly implements IReadOnly { /** * Constructs a new ReadOnly. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.TransactionOptions.IReadOnly); /** ReadOnly strong. */ public strong: boolean; /** ReadOnly minReadTimestamp. */ public minReadTimestamp?: (google.protobuf.ITimestamp|null); /** ReadOnly maxStaleness. */ public maxStaleness?: (google.protobuf.IDuration|null); /** ReadOnly readTimestamp. */ public readTimestamp?: (google.protobuf.ITimestamp|null); /** ReadOnly exactStaleness. */ public exactStaleness?: (google.protobuf.IDuration|null); /** ReadOnly returnReadTimestamp. */ public returnReadTimestamp: boolean; /** ReadOnly timestampBound. */ public timestampBound?: ("strong"|"minReadTimestamp"|"maxStaleness"|"readTimestamp"|"exactStaleness"); /** * Creates a new ReadOnly instance using the specified properties. * @param [properties] Properties to set * @returns ReadOnly instance */ public static create(properties?: google.spanner.v1.TransactionOptions.IReadOnly): google.spanner.v1.TransactionOptions.ReadOnly; /** * Encodes the specified ReadOnly message. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadOnly.verify|verify} messages. * @param message ReadOnly message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.TransactionOptions.IReadOnly, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ReadOnly message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionOptions.ReadOnly.verify|verify} messages. * @param message ReadOnly message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.TransactionOptions.IReadOnly, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ReadOnly message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ReadOnly * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.TransactionOptions.ReadOnly; /** * Decodes a ReadOnly message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ReadOnly * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.TransactionOptions.ReadOnly; /** * Verifies a ReadOnly message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ReadOnly message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ReadOnly */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.TransactionOptions.ReadOnly; /** * Creates a plain object from a ReadOnly message. Also converts values to other types if specified. * @param message ReadOnly * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.TransactionOptions.ReadOnly, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ReadOnly to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a Transaction. */ interface ITransaction { /** Transaction id */ id?: (Uint8Array|string|null); /** Transaction readTimestamp */ readTimestamp?: (google.protobuf.ITimestamp|null); } /** Represents a Transaction. */ class Transaction implements ITransaction { /** * Constructs a new Transaction. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.ITransaction); /** Transaction id. */ public id: (Uint8Array|string); /** Transaction readTimestamp. */ public readTimestamp?: (google.protobuf.ITimestamp|null); /** * Creates a new Transaction instance using the specified properties. * @param [properties] Properties to set * @returns Transaction instance */ public static create(properties?: google.spanner.v1.ITransaction): google.spanner.v1.Transaction; /** * Encodes the specified Transaction message. Does not implicitly {@link google.spanner.v1.Transaction.verify|verify} messages. * @param message Transaction message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.ITransaction, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Transaction message, length delimited. Does not implicitly {@link google.spanner.v1.Transaction.verify|verify} messages. * @param message Transaction message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.ITransaction, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Transaction message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Transaction * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Transaction; /** * Decodes a Transaction message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Transaction * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Transaction; /** * Verifies a Transaction message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Transaction message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Transaction */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.Transaction; /** * Creates a plain object from a Transaction message. Also converts values to other types if specified. * @param message Transaction * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.Transaction, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Transaction to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a TransactionSelector. */ interface ITransactionSelector { /** TransactionSelector singleUse */ singleUse?: (google.spanner.v1.ITransactionOptions|null); /** TransactionSelector id */ id?: (Uint8Array|string|null); /** TransactionSelector begin */ begin?: (google.spanner.v1.ITransactionOptions|null); } /** Represents a TransactionSelector. */ class TransactionSelector implements ITransactionSelector { /** * Constructs a new TransactionSelector. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.ITransactionSelector); /** TransactionSelector singleUse. */ public singleUse?: (google.spanner.v1.ITransactionOptions|null); /** TransactionSelector id. */ public id: (Uint8Array|string); /** TransactionSelector begin. */ public begin?: (google.spanner.v1.ITransactionOptions|null); /** TransactionSelector selector. */ public selector?: ("singleUse"|"id"|"begin"); /** * Creates a new TransactionSelector instance using the specified properties. * @param [properties] Properties to set * @returns TransactionSelector instance */ public static create(properties?: google.spanner.v1.ITransactionSelector): google.spanner.v1.TransactionSelector; /** * Encodes the specified TransactionSelector message. Does not implicitly {@link google.spanner.v1.TransactionSelector.verify|verify} messages. * @param message TransactionSelector message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.ITransactionSelector, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified TransactionSelector message, length delimited. Does not implicitly {@link google.spanner.v1.TransactionSelector.verify|verify} messages. * @param message TransactionSelector message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.ITransactionSelector, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a TransactionSelector message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns TransactionSelector * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.TransactionSelector; /** * Decodes a TransactionSelector message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns TransactionSelector * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.TransactionSelector; /** * Verifies a TransactionSelector message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a TransactionSelector message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns TransactionSelector */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.TransactionSelector; /** * Creates a plain object from a TransactionSelector message. Also converts values to other types if specified. * @param message TransactionSelector * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.TransactionSelector, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this TransactionSelector to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** TypeCode enum. */ enum TypeCode { TYPE_CODE_UNSPECIFIED = 0, BOOL = 1, INT64 = 2, FLOAT64 = 3, TIMESTAMP = 4, DATE = 5, STRING = 6, BYTES = 7, ARRAY = 8, STRUCT = 9 } /** Properties of a Type. */ interface IType { /** Type code */ code?: (google.spanner.v1.TypeCode|keyof typeof google.spanner.v1.TypeCode|null); /** Type arrayElementType */ arrayElementType?: (google.spanner.v1.IType|null); /** Type structType */ structType?: (google.spanner.v1.IStructType|null); } /** Represents a Type. */ class Type implements IType { /** * Constructs a new Type. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IType); /** Type code. */ public code: (google.spanner.v1.TypeCode|keyof typeof google.spanner.v1.TypeCode); /** Type arrayElementType. */ public arrayElementType?: (google.spanner.v1.IType|null); /** Type structType. */ public structType?: (google.spanner.v1.IStructType|null); /** * Creates a new Type instance using the specified properties. * @param [properties] Properties to set * @returns Type instance */ public static create(properties?: google.spanner.v1.IType): google.spanner.v1.Type; /** * Encodes the specified Type message. Does not implicitly {@link google.spanner.v1.Type.verify|verify} messages. * @param message Type message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IType, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Type message, length delimited. Does not implicitly {@link google.spanner.v1.Type.verify|verify} messages. * @param message Type message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IType, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Type message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Type * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.Type; /** * Decodes a Type message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Type * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.Type; /** * Verifies a Type message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Type message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Type */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.Type; /** * Creates a plain object from a Type message. Also converts values to other types if specified. * @param message Type * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.Type, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Type to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a StructType. */ interface IStructType { /** StructType fields */ fields?: (google.spanner.v1.StructType.IField[]|null); } /** Represents a StructType. */ class StructType implements IStructType { /** * Constructs a new StructType. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.IStructType); /** StructType fields. */ public fields: google.spanner.v1.StructType.IField[]; /** * Creates a new StructType instance using the specified properties. * @param [properties] Properties to set * @returns StructType instance */ public static create(properties?: google.spanner.v1.IStructType): google.spanner.v1.StructType; /** * Encodes the specified StructType message. Does not implicitly {@link google.spanner.v1.StructType.verify|verify} messages. * @param message StructType message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.IStructType, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified StructType message, length delimited. Does not implicitly {@link google.spanner.v1.StructType.verify|verify} messages. * @param message StructType message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.IStructType, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a StructType message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns StructType * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.StructType; /** * Decodes a StructType message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns StructType * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.StructType; /** * Verifies a StructType message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a StructType message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns StructType */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.StructType; /** * Creates a plain object from a StructType message. Also converts values to other types if specified. * @param message StructType * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.StructType, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this StructType to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace StructType { /** Properties of a Field. */ interface IField { /** Field name */ name?: (string|null); /** Field type */ type?: (google.spanner.v1.IType|null); } /** Represents a Field. */ class Field implements IField { /** * Constructs a new Field. * @param [properties] Properties to set */ constructor(properties?: google.spanner.v1.StructType.IField); /** Field name. */ public name: string; /** Field type. */ public type?: (google.spanner.v1.IType|null); /** * Creates a new Field instance using the specified properties. * @param [properties] Properties to set * @returns Field instance */ public static create(properties?: google.spanner.v1.StructType.IField): google.spanner.v1.StructType.Field; /** * Encodes the specified Field message. Does not implicitly {@link google.spanner.v1.StructType.Field.verify|verify} messages. * @param message Field message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.spanner.v1.StructType.IField, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Field message, length delimited. Does not implicitly {@link google.spanner.v1.StructType.Field.verify|verify} messages. * @param message Field message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.spanner.v1.StructType.IField, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Field message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Field * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.spanner.v1.StructType.Field; /** * Decodes a Field message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Field * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.spanner.v1.StructType.Field; /** * Verifies a Field message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Field message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Field */ public static fromObject(object: { [k: string]: any }): google.spanner.v1.StructType.Field; /** * Creates a plain object from a Field message. Also converts values to other types if specified. * @param message Field * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.spanner.v1.StructType.Field, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Field to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } } /** Namespace api. */ namespace api { /** Properties of a Http. */ interface IHttp { /** Http rules */ rules?: (google.api.IHttpRule[]|null); /** Http fullyDecodeReservedExpansion */ fullyDecodeReservedExpansion?: (boolean|null); } /** Represents a Http. */ class Http implements IHttp { /** * Constructs a new Http. * @param [properties] Properties to set */ constructor(properties?: google.api.IHttp); /** Http rules. */ public rules: google.api.IHttpRule[]; /** Http fullyDecodeReservedExpansion. */ public fullyDecodeReservedExpansion: boolean; /** * Creates a new Http instance using the specified properties. * @param [properties] Properties to set * @returns Http instance */ public static create(properties?: google.api.IHttp): google.api.Http; /** * Encodes the specified Http message. Does not implicitly {@link google.api.Http.verify|verify} messages. * @param message Http message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Http message, length delimited. Does not implicitly {@link google.api.Http.verify|verify} messages. * @param message Http message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IHttp, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Http message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Http * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.Http; /** * Decodes a Http message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Http * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.Http; /** * Verifies a Http message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Http message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Http */ public static fromObject(object: { [k: string]: any }): google.api.Http; /** * Creates a plain object from a Http message. Also converts values to other types if specified. * @param message Http * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.Http, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Http to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a HttpRule. */ interface IHttpRule { /** HttpRule selector */ selector?: (string|null); /** HttpRule get */ get?: (string|null); /** HttpRule put */ put?: (string|null); /** HttpRule post */ post?: (string|null); /** HttpRule delete */ "delete"?: (string|null); /** HttpRule patch */ patch?: (string|null); /** HttpRule custom */ custom?: (google.api.ICustomHttpPattern|null); /** HttpRule body */ body?: (string|null); /** HttpRule responseBody */ responseBody?: (string|null); /** HttpRule additionalBindings */ additionalBindings?: (google.api.IHttpRule[]|null); } /** Represents a HttpRule. */ class HttpRule implements IHttpRule { /** * Constructs a new HttpRule. * @param [properties] Properties to set */ constructor(properties?: google.api.IHttpRule); /** HttpRule selector. */ public selector: string; /** HttpRule get. */ public get: string; /** HttpRule put. */ public put: string; /** HttpRule post. */ public post: string; /** HttpRule delete. */ public delete: string; /** HttpRule patch. */ public patch: string; /** HttpRule custom. */ public custom?: (google.api.ICustomHttpPattern|null); /** HttpRule body. */ public body: string; /** HttpRule responseBody. */ public responseBody: string; /** HttpRule additionalBindings. */ public additionalBindings: google.api.IHttpRule[]; /** HttpRule pattern. */ public pattern?: ("get"|"put"|"post"|"delete"|"patch"|"custom"); /** * Creates a new HttpRule instance using the specified properties. * @param [properties] Properties to set * @returns HttpRule instance */ public static create(properties?: google.api.IHttpRule): google.api.HttpRule; /** * Encodes the specified HttpRule message. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. * @param message HttpRule message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified HttpRule message, length delimited. Does not implicitly {@link google.api.HttpRule.verify|verify} messages. * @param message HttpRule message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IHttpRule, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a HttpRule message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns HttpRule * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.HttpRule; /** * Decodes a HttpRule message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns HttpRule * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.HttpRule; /** * Verifies a HttpRule message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a HttpRule message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns HttpRule */ public static fromObject(object: { [k: string]: any }): google.api.HttpRule; /** * Creates a plain object from a HttpRule message. Also converts values to other types if specified. * @param message HttpRule * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.HttpRule, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this HttpRule to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CustomHttpPattern. */ interface ICustomHttpPattern { /** CustomHttpPattern kind */ kind?: (string|null); /** CustomHttpPattern path */ path?: (string|null); } /** Represents a CustomHttpPattern. */ class CustomHttpPattern implements ICustomHttpPattern { /** * Constructs a new CustomHttpPattern. * @param [properties] Properties to set */ constructor(properties?: google.api.ICustomHttpPattern); /** CustomHttpPattern kind. */ public kind: string; /** CustomHttpPattern path. */ public path: string; /** * Creates a new CustomHttpPattern instance using the specified properties. * @param [properties] Properties to set * @returns CustomHttpPattern instance */ public static create(properties?: google.api.ICustomHttpPattern): google.api.CustomHttpPattern; /** * Encodes the specified CustomHttpPattern message. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. * @param message CustomHttpPattern message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CustomHttpPattern message, length delimited. Does not implicitly {@link google.api.CustomHttpPattern.verify|verify} messages. * @param message CustomHttpPattern message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.ICustomHttpPattern, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CustomHttpPattern message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CustomHttpPattern * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.CustomHttpPattern; /** * Decodes a CustomHttpPattern message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CustomHttpPattern * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.CustomHttpPattern; /** * Verifies a CustomHttpPattern message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CustomHttpPattern message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CustomHttpPattern */ public static fromObject(object: { [k: string]: any }): google.api.CustomHttpPattern; /** * Creates a plain object from a CustomHttpPattern message. Also converts values to other types if specified. * @param message CustomHttpPattern * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.CustomHttpPattern, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CustomHttpPattern to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** FieldBehavior enum. */ enum FieldBehavior { FIELD_BEHAVIOR_UNSPECIFIED = 0, OPTIONAL = 1, REQUIRED = 2, OUTPUT_ONLY = 3, INPUT_ONLY = 4, IMMUTABLE = 5 } /** Properties of a ResourceDescriptor. */ interface IResourceDescriptor { /** ResourceDescriptor type */ type?: (string|null); /** ResourceDescriptor pattern */ pattern?: (string[]|null); /** ResourceDescriptor nameField */ nameField?: (string|null); /** ResourceDescriptor history */ history?: (google.api.ResourceDescriptor.History|keyof typeof google.api.ResourceDescriptor.History|null); /** ResourceDescriptor plural */ plural?: (string|null); /** ResourceDescriptor singular */ singular?: (string|null); } /** Represents a ResourceDescriptor. */ class ResourceDescriptor implements IResourceDescriptor { /** * Constructs a new ResourceDescriptor. * @param [properties] Properties to set */ constructor(properties?: google.api.IResourceDescriptor); /** ResourceDescriptor type. */ public type: string; /** ResourceDescriptor pattern. */ public pattern: string[]; /** ResourceDescriptor nameField. */ public nameField: string; /** ResourceDescriptor history. */ public history: (google.api.ResourceDescriptor.History|keyof typeof google.api.ResourceDescriptor.History); /** ResourceDescriptor plural. */ public plural: string; /** ResourceDescriptor singular. */ public singular: string; /** * Creates a new ResourceDescriptor instance using the specified properties. * @param [properties] Properties to set * @returns ResourceDescriptor instance */ public static create(properties?: google.api.IResourceDescriptor): google.api.ResourceDescriptor; /** * Encodes the specified ResourceDescriptor message. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. * @param message ResourceDescriptor message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IResourceDescriptor, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ResourceDescriptor message, length delimited. Does not implicitly {@link google.api.ResourceDescriptor.verify|verify} messages. * @param message ResourceDescriptor message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IResourceDescriptor, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ResourceDescriptor message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ResourceDescriptor * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ResourceDescriptor; /** * Decodes a ResourceDescriptor message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ResourceDescriptor * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ResourceDescriptor; /** * Verifies a ResourceDescriptor message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ResourceDescriptor message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ResourceDescriptor */ public static fromObject(object: { [k: string]: any }): google.api.ResourceDescriptor; /** * Creates a plain object from a ResourceDescriptor message. Also converts values to other types if specified. * @param message ResourceDescriptor * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.ResourceDescriptor, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ResourceDescriptor to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace ResourceDescriptor { /** History enum. */ enum History { HISTORY_UNSPECIFIED = 0, ORIGINALLY_SINGLE_PATTERN = 1, FUTURE_MULTI_PATTERN = 2 } } /** Properties of a ResourceReference. */ interface IResourceReference { /** ResourceReference type */ type?: (string|null); /** ResourceReference childType */ childType?: (string|null); } /** Represents a ResourceReference. */ class ResourceReference implements IResourceReference { /** * Constructs a new ResourceReference. * @param [properties] Properties to set */ constructor(properties?: google.api.IResourceReference); /** ResourceReference type. */ public type: string; /** ResourceReference childType. */ public childType: string; /** * Creates a new ResourceReference instance using the specified properties. * @param [properties] Properties to set * @returns ResourceReference instance */ public static create(properties?: google.api.IResourceReference): google.api.ResourceReference; /** * Encodes the specified ResourceReference message. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. * @param message ResourceReference message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.api.IResourceReference, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ResourceReference message, length delimited. Does not implicitly {@link google.api.ResourceReference.verify|verify} messages. * @param message ResourceReference message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.api.IResourceReference, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ResourceReference message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ResourceReference * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.api.ResourceReference; /** * Decodes a ResourceReference message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ResourceReference * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.api.ResourceReference; /** * Verifies a ResourceReference message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ResourceReference message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ResourceReference */ public static fromObject(object: { [k: string]: any }): google.api.ResourceReference; /** * Creates a plain object from a ResourceReference message. Also converts values to other types if specified. * @param message ResourceReference * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.api.ResourceReference, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ResourceReference to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Namespace iam. */ namespace iam { /** Namespace v1. */ namespace v1 { /** Represents a IAMPolicy */ class IAMPolicy extends $protobuf.rpc.Service { /** * Constructs a new IAMPolicy service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new IAMPolicy service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): IAMPolicy; /** * Calls SetIamPolicy. * @param request SetIamPolicyRequest message or plain object * @param callback Node-style callback called with the error, if any, and Policy */ public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest, callback: google.iam.v1.IAMPolicy.SetIamPolicyCallback): void; /** * Calls SetIamPolicy. * @param request SetIamPolicyRequest message or plain object * @returns Promise */ public setIamPolicy(request: google.iam.v1.ISetIamPolicyRequest): Promise<google.iam.v1.Policy>; /** * Calls GetIamPolicy. * @param request GetIamPolicyRequest message or plain object * @param callback Node-style callback called with the error, if any, and Policy */ public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest, callback: google.iam.v1.IAMPolicy.GetIamPolicyCallback): void; /** * Calls GetIamPolicy. * @param request GetIamPolicyRequest message or plain object * @returns Promise */ public getIamPolicy(request: google.iam.v1.IGetIamPolicyRequest): Promise<google.iam.v1.Policy>; /** * Calls TestIamPermissions. * @param request TestIamPermissionsRequest message or plain object * @param callback Node-style callback called with the error, if any, and TestIamPermissionsResponse */ public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest, callback: google.iam.v1.IAMPolicy.TestIamPermissionsCallback): void; /** * Calls TestIamPermissions. * @param request TestIamPermissionsRequest message or plain object * @returns Promise */ public testIamPermissions(request: google.iam.v1.ITestIamPermissionsRequest): Promise<google.iam.v1.TestIamPermissionsResponse>; } namespace IAMPolicy { /** * Callback as used by {@link google.iam.v1.IAMPolicy#setIamPolicy}. * @param error Error, if any * @param [response] Policy */ type SetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; /** * Callback as used by {@link google.iam.v1.IAMPolicy#getIamPolicy}. * @param error Error, if any * @param [response] Policy */ type GetIamPolicyCallback = (error: (Error|null), response?: google.iam.v1.Policy) => void; /** * Callback as used by {@link google.iam.v1.IAMPolicy#testIamPermissions}. * @param error Error, if any * @param [response] TestIamPermissionsResponse */ type TestIamPermissionsCallback = (error: (Error|null), response?: google.iam.v1.TestIamPermissionsResponse) => void; } /** Properties of a SetIamPolicyRequest. */ interface ISetIamPolicyRequest { /** SetIamPolicyRequest resource */ resource?: (string|null); /** SetIamPolicyRequest policy */ policy?: (google.iam.v1.IPolicy|null); } /** Represents a SetIamPolicyRequest. */ class SetIamPolicyRequest implements ISetIamPolicyRequest { /** * Constructs a new SetIamPolicyRequest. * @param [properties] Properties to set */ constructor(properties?: google.iam.v1.ISetIamPolicyRequest); /** SetIamPolicyRequest resource. */ public resource: string; /** SetIamPolicyRequest policy. */ public policy?: (google.iam.v1.IPolicy|null); /** * Creates a new SetIamPolicyRequest instance using the specified properties. * @param [properties] Properties to set * @returns SetIamPolicyRequest instance */ public static create(properties?: google.iam.v1.ISetIamPolicyRequest): google.iam.v1.SetIamPolicyRequest; /** * Encodes the specified SetIamPolicyRequest message. Does not implicitly {@link google.iam.v1.SetIamPolicyRequest.verify|verify} messages. * @param message SetIamPolicyRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.iam.v1.ISetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified SetIamPolicyRequest message, length delimited. Does not implicitly {@link google.iam.v1.SetIamPolicyRequest.verify|verify} messages. * @param message SetIamPolicyRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.iam.v1.ISetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SetIamPolicyRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns SetIamPolicyRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.SetIamPolicyRequest; /** * Decodes a SetIamPolicyRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns SetIamPolicyRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.SetIamPolicyRequest; /** * Verifies a SetIamPolicyRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a SetIamPolicyRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns SetIamPolicyRequest */ public static fromObject(object: { [k: string]: any }): google.iam.v1.SetIamPolicyRequest; /** * Creates a plain object from a SetIamPolicyRequest message. Also converts values to other types if specified. * @param message SetIamPolicyRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.iam.v1.SetIamPolicyRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SetIamPolicyRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetIamPolicyRequest. */ interface IGetIamPolicyRequest { /** GetIamPolicyRequest resource */ resource?: (string|null); /** GetIamPolicyRequest options */ options?: (google.iam.v1.IGetPolicyOptions|null); } /** Represents a GetIamPolicyRequest. */ class GetIamPolicyRequest implements IGetIamPolicyRequest { /** * Constructs a new GetIamPolicyRequest. * @param [properties] Properties to set */ constructor(properties?: google.iam.v1.IGetIamPolicyRequest); /** GetIamPolicyRequest resource. */ public resource: string; /** GetIamPolicyRequest options. */ public options?: (google.iam.v1.IGetPolicyOptions|null); /** * Creates a new GetIamPolicyRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetIamPolicyRequest instance */ public static create(properties?: google.iam.v1.IGetIamPolicyRequest): google.iam.v1.GetIamPolicyRequest; /** * Encodes the specified GetIamPolicyRequest message. Does not implicitly {@link google.iam.v1.GetIamPolicyRequest.verify|verify} messages. * @param message GetIamPolicyRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.iam.v1.IGetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetIamPolicyRequest message, length delimited. Does not implicitly {@link google.iam.v1.GetIamPolicyRequest.verify|verify} messages. * @param message GetIamPolicyRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.iam.v1.IGetIamPolicyRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetIamPolicyRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetIamPolicyRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.GetIamPolicyRequest; /** * Decodes a GetIamPolicyRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetIamPolicyRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.GetIamPolicyRequest; /** * Verifies a GetIamPolicyRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetIamPolicyRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetIamPolicyRequest */ public static fromObject(object: { [k: string]: any }): google.iam.v1.GetIamPolicyRequest; /** * Creates a plain object from a GetIamPolicyRequest message. Also converts values to other types if specified. * @param message GetIamPolicyRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.iam.v1.GetIamPolicyRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetIamPolicyRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a TestIamPermissionsRequest. */ interface ITestIamPermissionsRequest { /** TestIamPermissionsRequest resource */ resource?: (string|null); /** TestIamPermissionsRequest permissions */ permissions?: (string[]|null); } /** Represents a TestIamPermissionsRequest. */ class TestIamPermissionsRequest implements ITestIamPermissionsRequest { /** * Constructs a new TestIamPermissionsRequest. * @param [properties] Properties to set */ constructor(properties?: google.iam.v1.ITestIamPermissionsRequest); /** TestIamPermissionsRequest resource. */ public resource: string; /** TestIamPermissionsRequest permissions. */ public permissions: string[]; /** * Creates a new TestIamPermissionsRequest instance using the specified properties. * @param [properties] Properties to set * @returns TestIamPermissionsRequest instance */ public static create(properties?: google.iam.v1.ITestIamPermissionsRequest): google.iam.v1.TestIamPermissionsRequest; /** * Encodes the specified TestIamPermissionsRequest message. Does not implicitly {@link google.iam.v1.TestIamPermissionsRequest.verify|verify} messages. * @param message TestIamPermissionsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.iam.v1.ITestIamPermissionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified TestIamPermissionsRequest message, length delimited. Does not implicitly {@link google.iam.v1.TestIamPermissionsRequest.verify|verify} messages. * @param message TestIamPermissionsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.iam.v1.ITestIamPermissionsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a TestIamPermissionsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns TestIamPermissionsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.TestIamPermissionsRequest; /** * Decodes a TestIamPermissionsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns TestIamPermissionsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.TestIamPermissionsRequest; /** * Verifies a TestIamPermissionsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a TestIamPermissionsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns TestIamPermissionsRequest */ public static fromObject(object: { [k: string]: any }): google.iam.v1.TestIamPermissionsRequest; /** * Creates a plain object from a TestIamPermissionsRequest message. Also converts values to other types if specified. * @param message TestIamPermissionsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.iam.v1.TestIamPermissionsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this TestIamPermissionsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a TestIamPermissionsResponse. */ interface ITestIamPermissionsResponse { /** TestIamPermissionsResponse permissions */ permissions?: (string[]|null); } /** Represents a TestIamPermissionsResponse. */ class TestIamPermissionsResponse implements ITestIamPermissionsResponse { /** * Constructs a new TestIamPermissionsResponse. * @param [properties] Properties to set */ constructor(properties?: google.iam.v1.ITestIamPermissionsResponse); /** TestIamPermissionsResponse permissions. */ public permissions: string[]; /** * Creates a new TestIamPermissionsResponse instance using the specified properties. * @param [properties] Properties to set * @returns TestIamPermissionsResponse instance */ public static create(properties?: google.iam.v1.ITestIamPermissionsResponse): google.iam.v1.TestIamPermissionsResponse; /** * Encodes the specified TestIamPermissionsResponse message. Does not implicitly {@link google.iam.v1.TestIamPermissionsResponse.verify|verify} messages. * @param message TestIamPermissionsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.iam.v1.ITestIamPermissionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified TestIamPermissionsResponse message, length delimited. Does not implicitly {@link google.iam.v1.TestIamPermissionsResponse.verify|verify} messages. * @param message TestIamPermissionsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.iam.v1.ITestIamPermissionsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a TestIamPermissionsResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns TestIamPermissionsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.TestIamPermissionsResponse; /** * Decodes a TestIamPermissionsResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns TestIamPermissionsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.TestIamPermissionsResponse; /** * Verifies a TestIamPermissionsResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a TestIamPermissionsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns TestIamPermissionsResponse */ public static fromObject(object: { [k: string]: any }): google.iam.v1.TestIamPermissionsResponse; /** * Creates a plain object from a TestIamPermissionsResponse message. Also converts values to other types if specified. * @param message TestIamPermissionsResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.iam.v1.TestIamPermissionsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this TestIamPermissionsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetPolicyOptions. */ interface IGetPolicyOptions { /** GetPolicyOptions requestedPolicyVersion */ requestedPolicyVersion?: (number|null); } /** Represents a GetPolicyOptions. */ class GetPolicyOptions implements IGetPolicyOptions { /** * Constructs a new GetPolicyOptions. * @param [properties] Properties to set */ constructor(properties?: google.iam.v1.IGetPolicyOptions); /** GetPolicyOptions requestedPolicyVersion. */ public requestedPolicyVersion: number; /** * Creates a new GetPolicyOptions instance using the specified properties. * @param [properties] Properties to set * @returns GetPolicyOptions instance */ public static create(properties?: google.iam.v1.IGetPolicyOptions): google.iam.v1.GetPolicyOptions; /** * Encodes the specified GetPolicyOptions message. Does not implicitly {@link google.iam.v1.GetPolicyOptions.verify|verify} messages. * @param message GetPolicyOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.iam.v1.IGetPolicyOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetPolicyOptions message, length delimited. Does not implicitly {@link google.iam.v1.GetPolicyOptions.verify|verify} messages. * @param message GetPolicyOptions message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.iam.v1.IGetPolicyOptions, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetPolicyOptions message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetPolicyOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.GetPolicyOptions; /** * Decodes a GetPolicyOptions message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetPolicyOptions * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.GetPolicyOptions; /** * Verifies a GetPolicyOptions message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetPolicyOptions message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetPolicyOptions */ public static fromObject(object: { [k: string]: any }): google.iam.v1.GetPolicyOptions; /** * Creates a plain object from a GetPolicyOptions message. Also converts values to other types if specified. * @param message GetPolicyOptions * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.iam.v1.GetPolicyOptions, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetPolicyOptions to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Policy. */ interface IPolicy { /** Policy version */ version?: (number|null); /** Policy bindings */ bindings?: (google.iam.v1.IBinding[]|null); /** Policy etag */ etag?: (Uint8Array|string|null); } /** Represents a Policy. */ class Policy implements IPolicy { /** * Constructs a new Policy. * @param [properties] Properties to set */ constructor(properties?: google.iam.v1.IPolicy); /** Policy version. */ public version: number; /** Policy bindings. */ public bindings: google.iam.v1.IBinding[]; /** Policy etag. */ public etag: (Uint8Array|string); /** * Creates a new Policy instance using the specified properties. * @param [properties] Properties to set * @returns Policy instance */ public static create(properties?: google.iam.v1.IPolicy): google.iam.v1.Policy; /** * Encodes the specified Policy message. Does not implicitly {@link google.iam.v1.Policy.verify|verify} messages. * @param message Policy message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.iam.v1.IPolicy, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Policy message, length delimited. Does not implicitly {@link google.iam.v1.Policy.verify|verify} messages. * @param message Policy message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.iam.v1.IPolicy, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Policy message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Policy * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.Policy; /** * Decodes a Policy message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Policy * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.Policy; /** * Verifies a Policy message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Policy message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Policy */ public static fromObject(object: { [k: string]: any }): google.iam.v1.Policy; /** * Creates a plain object from a Policy message. Also converts values to other types if specified. * @param message Policy * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.iam.v1.Policy, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Policy to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Binding. */ interface IBinding { /** Binding role */ role?: (string|null); /** Binding members */ members?: (string[]|null); /** Binding condition */ condition?: (google.type.IExpr|null); } /** Represents a Binding. */ class Binding implements IBinding { /** * Constructs a new Binding. * @param [properties] Properties to set */ constructor(properties?: google.iam.v1.IBinding); /** Binding role. */ public role: string; /** Binding members. */ public members: string[]; /** Binding condition. */ public condition?: (google.type.IExpr|null); /** * Creates a new Binding instance using the specified properties. * @param [properties] Properties to set * @returns Binding instance */ public static create(properties?: google.iam.v1.IBinding): google.iam.v1.Binding; /** * Encodes the specified Binding message. Does not implicitly {@link google.iam.v1.Binding.verify|verify} messages. * @param message Binding message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.iam.v1.IBinding, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Binding message, length delimited. Does not implicitly {@link google.iam.v1.Binding.verify|verify} messages. * @param message Binding message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.iam.v1.IBinding, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Binding message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Binding * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.Binding; /** * Decodes a Binding message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Binding * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.Binding; /** * Verifies a Binding message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Binding message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Binding */ public static fromObject(object: { [k: string]: any }): google.iam.v1.Binding; /** * Creates a plain object from a Binding message. Also converts values to other types if specified. * @param message Binding * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.iam.v1.Binding, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Binding to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PolicyDelta. */ interface IPolicyDelta { /** PolicyDelta bindingDeltas */ bindingDeltas?: (google.iam.v1.IBindingDelta[]|null); /** PolicyDelta auditConfigDeltas */ auditConfigDeltas?: (google.iam.v1.IAuditConfigDelta[]|null); } /** Represents a PolicyDelta. */ class PolicyDelta implements IPolicyDelta { /** * Constructs a new PolicyDelta. * @param [properties] Properties to set */ constructor(properties?: google.iam.v1.IPolicyDelta); /** PolicyDelta bindingDeltas. */ public bindingDeltas: google.iam.v1.IBindingDelta[]; /** PolicyDelta auditConfigDeltas. */ public auditConfigDeltas: google.iam.v1.IAuditConfigDelta[]; /** * Creates a new PolicyDelta instance using the specified properties. * @param [properties] Properties to set * @returns PolicyDelta instance */ public static create(properties?: google.iam.v1.IPolicyDelta): google.iam.v1.PolicyDelta; /** * Encodes the specified PolicyDelta message. Does not implicitly {@link google.iam.v1.PolicyDelta.verify|verify} messages. * @param message PolicyDelta message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.iam.v1.IPolicyDelta, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PolicyDelta message, length delimited. Does not implicitly {@link google.iam.v1.PolicyDelta.verify|verify} messages. * @param message PolicyDelta message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.iam.v1.IPolicyDelta, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PolicyDelta message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PolicyDelta * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.PolicyDelta; /** * Decodes a PolicyDelta message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PolicyDelta * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.PolicyDelta; /** * Verifies a PolicyDelta message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PolicyDelta message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PolicyDelta */ public static fromObject(object: { [k: string]: any }): google.iam.v1.PolicyDelta; /** * Creates a plain object from a PolicyDelta message. Also converts values to other types if specified. * @param message PolicyDelta * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.iam.v1.PolicyDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PolicyDelta to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a BindingDelta. */ interface IBindingDelta { /** BindingDelta action */ action?: (google.iam.v1.BindingDelta.Action|keyof typeof google.iam.v1.BindingDelta.Action|null); /** BindingDelta role */ role?: (string|null); /** BindingDelta member */ member?: (string|null); /** BindingDelta condition */ condition?: (google.type.IExpr|null); } /** Represents a BindingDelta. */ class BindingDelta implements IBindingDelta { /** * Constructs a new BindingDelta. * @param [properties] Properties to set */ constructor(properties?: google.iam.v1.IBindingDelta); /** BindingDelta action. */ public action: (google.iam.v1.BindingDelta.Action|keyof typeof google.iam.v1.BindingDelta.Action); /** BindingDelta role. */ public role: string; /** BindingDelta member. */ public member: string; /** BindingDelta condition. */ public condition?: (google.type.IExpr|null); /** * Creates a new BindingDelta instance using the specified properties. * @param [properties] Properties to set * @returns BindingDelta instance */ public static create(properties?: google.iam.v1.IBindingDelta): google.iam.v1.BindingDelta; /** * Encodes the specified BindingDelta message. Does not implicitly {@link google.iam.v1.BindingDelta.verify|verify} messages. * @param message BindingDelta message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.iam.v1.IBindingDelta, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified BindingDelta message, length delimited. Does not implicitly {@link google.iam.v1.BindingDelta.verify|verify} messages. * @param message BindingDelta message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.iam.v1.IBindingDelta, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a BindingDelta message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns BindingDelta * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.BindingDelta; /** * Decodes a BindingDelta message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns BindingDelta * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.BindingDelta; /** * Verifies a BindingDelta message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a BindingDelta message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns BindingDelta */ public static fromObject(object: { [k: string]: any }): google.iam.v1.BindingDelta; /** * Creates a plain object from a BindingDelta message. Also converts values to other types if specified. * @param message BindingDelta * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.iam.v1.BindingDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this BindingDelta to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace BindingDelta { /** Action enum. */ enum Action { ACTION_UNSPECIFIED = 0, ADD = 1, REMOVE = 2 } } /** Properties of an AuditConfigDelta. */ interface IAuditConfigDelta { /** AuditConfigDelta action */ action?: (google.iam.v1.AuditConfigDelta.Action|keyof typeof google.iam.v1.AuditConfigDelta.Action|null); /** AuditConfigDelta service */ service?: (string|null); /** AuditConfigDelta exemptedMember */ exemptedMember?: (string|null); /** AuditConfigDelta logType */ logType?: (string|null); } /** Represents an AuditConfigDelta. */ class AuditConfigDelta implements IAuditConfigDelta { /** * Constructs a new AuditConfigDelta. * @param [properties] Properties to set */ constructor(properties?: google.iam.v1.IAuditConfigDelta); /** AuditConfigDelta action. */ public action: (google.iam.v1.AuditConfigDelta.Action|keyof typeof google.iam.v1.AuditConfigDelta.Action); /** AuditConfigDelta service. */ public service: string; /** AuditConfigDelta exemptedMember. */ public exemptedMember: string; /** AuditConfigDelta logType. */ public logType: string; /** * Creates a new AuditConfigDelta instance using the specified properties. * @param [properties] Properties to set * @returns AuditConfigDelta instance */ public static create(properties?: google.iam.v1.IAuditConfigDelta): google.iam.v1.AuditConfigDelta; /** * Encodes the specified AuditConfigDelta message. Does not implicitly {@link google.iam.v1.AuditConfigDelta.verify|verify} messages. * @param message AuditConfigDelta message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.iam.v1.IAuditConfigDelta, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified AuditConfigDelta message, length delimited. Does not implicitly {@link google.iam.v1.AuditConfigDelta.verify|verify} messages. * @param message AuditConfigDelta message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.iam.v1.IAuditConfigDelta, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an AuditConfigDelta message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns AuditConfigDelta * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.iam.v1.AuditConfigDelta; /** * Decodes an AuditConfigDelta message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns AuditConfigDelta * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.iam.v1.AuditConfigDelta; /** * Verifies an AuditConfigDelta message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an AuditConfigDelta message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns AuditConfigDelta */ public static fromObject(object: { [k: string]: any }): google.iam.v1.AuditConfigDelta; /** * Creates a plain object from an AuditConfigDelta message. Also converts values to other types if specified. * @param message AuditConfigDelta * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.iam.v1.AuditConfigDelta, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this AuditConfigDelta to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace AuditConfigDelta { /** Action enum. */ enum Action { ACTION_UNSPECIFIED = 0, ADD = 1, REMOVE = 2 } } } } /** Namespace type. */ namespace type { /** Properties of an Expr. */ interface IExpr { /** Expr expression */ expression?: (string|null); /** Expr title */ title?: (string|null); /** Expr description */ description?: (string|null); /** Expr location */ location?: (string|null); } /** Represents an Expr. */ class Expr implements IExpr { /** * Constructs a new Expr. * @param [properties] Properties to set */ constructor(properties?: google.type.IExpr); /** Expr expression. */ public expression: string; /** Expr title. */ public title: string; /** Expr description. */ public description: string; /** Expr location. */ public location: string; /** * Creates a new Expr instance using the specified properties. * @param [properties] Properties to set * @returns Expr instance */ public static create(properties?: google.type.IExpr): google.type.Expr; /** * Encodes the specified Expr message. Does not implicitly {@link google.type.Expr.verify|verify} messages. * @param message Expr message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.type.IExpr, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Expr message, length delimited. Does not implicitly {@link google.type.Expr.verify|verify} messages. * @param message Expr message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.type.IExpr, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Expr message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Expr * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.type.Expr; /** * Decodes an Expr message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Expr * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.type.Expr; /** * Verifies an Expr message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Expr message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Expr */ public static fromObject(object: { [k: string]: any }): google.type.Expr; /** * Creates a plain object from an Expr message. Also converts values to other types if specified. * @param message Expr * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.type.Expr, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Expr to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Namespace longrunning. */ namespace longrunning { /** Represents an Operations */ class Operations extends $protobuf.rpc.Service { /** * Constructs a new Operations service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new Operations service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Operations; /** * Calls ListOperations. * @param request ListOperationsRequest message or plain object * @param callback Node-style callback called with the error, if any, and ListOperationsResponse */ public listOperations(request: google.longrunning.IListOperationsRequest, callback: google.longrunning.Operations.ListOperationsCallback): void; /** * Calls ListOperations. * @param request ListOperationsRequest message or plain object * @returns Promise */ public listOperations(request: google.longrunning.IListOperationsRequest): Promise<google.longrunning.ListOperationsResponse>; /** * Calls GetOperation. * @param request GetOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public getOperation(request: google.longrunning.IGetOperationRequest, callback: google.longrunning.Operations.GetOperationCallback): void; /** * Calls GetOperation. * @param request GetOperationRequest message or plain object * @returns Promise */ public getOperation(request: google.longrunning.IGetOperationRequest): Promise<google.longrunning.Operation>; /** * Calls DeleteOperation. * @param request DeleteOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Empty */ public deleteOperation(request: google.longrunning.IDeleteOperationRequest, callback: google.longrunning.Operations.DeleteOperationCallback): void; /** * Calls DeleteOperation. * @param request DeleteOperationRequest message or plain object * @returns Promise */ public deleteOperation(request: google.longrunning.IDeleteOperationRequest): Promise<google.protobuf.Empty>; /** * Calls CancelOperation. * @param request CancelOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Empty */ public cancelOperation(request: google.longrunning.ICancelOperationRequest, callback: google.longrunning.Operations.CancelOperationCallback): void; /** * Calls CancelOperation. * @param request CancelOperationRequest message or plain object * @returns Promise */ public cancelOperation(request: google.longrunning.ICancelOperationRequest): Promise<google.protobuf.Empty>; /** * Calls WaitOperation. * @param request WaitOperationRequest message or plain object * @param callback Node-style callback called with the error, if any, and Operation */ public waitOperation(request: google.longrunning.IWaitOperationRequest, callback: google.longrunning.Operations.WaitOperationCallback): void; /** * Calls WaitOperation. * @param request WaitOperationRequest message or plain object * @returns Promise */ public waitOperation(request: google.longrunning.IWaitOperationRequest): Promise<google.longrunning.Operation>; } namespace Operations { /** * Callback as used by {@link google.longrunning.Operations#listOperations}. * @param error Error, if any * @param [response] ListOperationsResponse */ type ListOperationsCallback = (error: (Error|null), response?: google.longrunning.ListOperationsResponse) => void; /** * Callback as used by {@link google.longrunning.Operations#getOperation}. * @param error Error, if any * @param [response] Operation */ type GetOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; /** * Callback as used by {@link google.longrunning.Operations#deleteOperation}. * @param error Error, if any * @param [response] Empty */ type DeleteOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; /** * Callback as used by {@link google.longrunning.Operations#cancelOperation}. * @param error Error, if any * @param [response] Empty */ type CancelOperationCallback = (error: (Error|null), response?: google.protobuf.Empty) => void; /** * Callback as used by {@link google.longrunning.Operations#waitOperation}. * @param error Error, if any * @param [response] Operation */ type WaitOperationCallback = (error: (Error|null), response?: google.longrunning.Operation) => void; } /** Properties of an Operation. */ interface IOperation { /** Operation name */ name?: (string|null); /** Operation metadata */ metadata?: (google.protobuf.IAny|null); /** Operation done */ done?: (boolean|null); /** Operation error */ error?: (google.rpc.IStatus|null); /** Operation response */ response?: (google.protobuf.IAny|null); } /** Represents an Operation. */ class Operation implements IOperation { /** * Constructs a new Operation. * @param [properties] Properties to set */ constructor(properties?: google.longrunning.IOperation); /** Operation name. */ public name: string; /** Operation metadata. */ public metadata?: (google.protobuf.IAny|null); /** Operation done. */ public done: boolean; /** Operation error. */ public error?: (google.rpc.IStatus|null); /** Operation response. */ public response?: (google.protobuf.IAny|null); /** Operation result. */ public result?: ("error"|"response"); /** * Creates a new Operation instance using the specified properties. * @param [properties] Properties to set * @returns Operation instance */ public static create(properties?: google.longrunning.IOperation): google.longrunning.Operation; /** * Encodes the specified Operation message. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages. * @param message Operation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.longrunning.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Operation message, length delimited. Does not implicitly {@link google.longrunning.Operation.verify|verify} messages. * @param message Operation message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.longrunning.IOperation, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Operation message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Operation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.Operation; /** * Decodes an Operation message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Operation * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.Operation; /** * Verifies an Operation message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Operation message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Operation */ public static fromObject(object: { [k: string]: any }): google.longrunning.Operation; /** * Creates a plain object from an Operation message. Also converts values to other types if specified. * @param message Operation * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.longrunning.Operation, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Operation to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a GetOperationRequest. */ interface IGetOperationRequest { /** GetOperationRequest name */ name?: (string|null); } /** Represents a GetOperationRequest. */ class GetOperationRequest implements IGetOperationRequest { /** * Constructs a new GetOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.longrunning.IGetOperationRequest); /** GetOperationRequest name. */ public name: string; /** * Creates a new GetOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns GetOperationRequest instance */ public static create(properties?: google.longrunning.IGetOperationRequest): google.longrunning.GetOperationRequest; /** * Encodes the specified GetOperationRequest message. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages. * @param message GetOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.longrunning.IGetOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified GetOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.GetOperationRequest.verify|verify} messages. * @param message GetOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.longrunning.IGetOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a GetOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns GetOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.GetOperationRequest; /** * Decodes a GetOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns GetOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.GetOperationRequest; /** * Verifies a GetOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a GetOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns GetOperationRequest */ public static fromObject(object: { [k: string]: any }): google.longrunning.GetOperationRequest; /** * Creates a plain object from a GetOperationRequest message. Also converts values to other types if specified. * @param message GetOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.longrunning.GetOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this GetOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListOperationsRequest. */ interface IListOperationsRequest { /** ListOperationsRequest name */ name?: (string|null); /** ListOperationsRequest filter */ filter?: (string|null); /** ListOperationsRequest pageSize */ pageSize?: (number|null); /** ListOperationsRequest pageToken */ pageToken?: (string|null); } /** Represents a ListOperationsRequest. */ class ListOperationsRequest implements IListOperationsRequest { /** * Constructs a new ListOperationsRequest. * @param [properties] Properties to set */ constructor(properties?: google.longrunning.IListOperationsRequest); /** ListOperationsRequest name. */ public name: string; /** ListOperationsRequest filter. */ public filter: string; /** ListOperationsRequest pageSize. */ public pageSize: number; /** ListOperationsRequest pageToken. */ public pageToken: string; /** * Creates a new ListOperationsRequest instance using the specified properties. * @param [properties] Properties to set * @returns ListOperationsRequest instance */ public static create(properties?: google.longrunning.IListOperationsRequest): google.longrunning.ListOperationsRequest; /** * Encodes the specified ListOperationsRequest message. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages. * @param message ListOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.longrunning.IListOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListOperationsRequest message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsRequest.verify|verify} messages. * @param message ListOperationsRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.longrunning.IListOperationsRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListOperationsRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.ListOperationsRequest; /** * Decodes a ListOperationsRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListOperationsRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.ListOperationsRequest; /** * Verifies a ListOperationsRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListOperationsRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListOperationsRequest */ public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsRequest; /** * Creates a plain object from a ListOperationsRequest message. Also converts values to other types if specified. * @param message ListOperationsRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.longrunning.ListOperationsRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListOperationsRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ListOperationsResponse. */ interface IListOperationsResponse { /** ListOperationsResponse operations */ operations?: (google.longrunning.IOperation[]|null); /** ListOperationsResponse nextPageToken */ nextPageToken?: (string|null); } /** Represents a ListOperationsResponse. */ class ListOperationsResponse implements IListOperationsResponse { /** * Constructs a new ListOperationsResponse. * @param [properties] Properties to set */ constructor(properties?: google.longrunning.IListOperationsResponse); /** ListOperationsResponse operations. */ public operations: google.longrunning.IOperation[]; /** ListOperationsResponse nextPageToken. */ public nextPageToken: string; /** * Creates a new ListOperationsResponse instance using the specified properties. * @param [properties] Properties to set * @returns ListOperationsResponse instance */ public static create(properties?: google.longrunning.IListOperationsResponse): google.longrunning.ListOperationsResponse; /** * Encodes the specified ListOperationsResponse message. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages. * @param message ListOperationsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.longrunning.IListOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ListOperationsResponse message, length delimited. Does not implicitly {@link google.longrunning.ListOperationsResponse.verify|verify} messages. * @param message ListOperationsResponse message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.longrunning.IListOperationsResponse, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ListOperationsResponse message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ListOperationsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.ListOperationsResponse; /** * Decodes a ListOperationsResponse message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ListOperationsResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.ListOperationsResponse; /** * Verifies a ListOperationsResponse message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ListOperationsResponse message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ListOperationsResponse */ public static fromObject(object: { [k: string]: any }): google.longrunning.ListOperationsResponse; /** * Creates a plain object from a ListOperationsResponse message. Also converts values to other types if specified. * @param message ListOperationsResponse * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.longrunning.ListOperationsResponse, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ListOperationsResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CancelOperationRequest. */ interface ICancelOperationRequest { /** CancelOperationRequest name */ name?: (string|null); } /** Represents a CancelOperationRequest. */ class CancelOperationRequest implements ICancelOperationRequest { /** * Constructs a new CancelOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.longrunning.ICancelOperationRequest); /** CancelOperationRequest name. */ public name: string; /** * Creates a new CancelOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns CancelOperationRequest instance */ public static create(properties?: google.longrunning.ICancelOperationRequest): google.longrunning.CancelOperationRequest; /** * Encodes the specified CancelOperationRequest message. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages. * @param message CancelOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.longrunning.ICancelOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified CancelOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.CancelOperationRequest.verify|verify} messages. * @param message CancelOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.longrunning.ICancelOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CancelOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns CancelOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.CancelOperationRequest; /** * Decodes a CancelOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns CancelOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.CancelOperationRequest; /** * Verifies a CancelOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a CancelOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns CancelOperationRequest */ public static fromObject(object: { [k: string]: any }): google.longrunning.CancelOperationRequest; /** * Creates a plain object from a CancelOperationRequest message. Also converts values to other types if specified. * @param message CancelOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.longrunning.CancelOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CancelOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DeleteOperationRequest. */ interface IDeleteOperationRequest { /** DeleteOperationRequest name */ name?: (string|null); } /** Represents a DeleteOperationRequest. */ class DeleteOperationRequest implements IDeleteOperationRequest { /** * Constructs a new DeleteOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.longrunning.IDeleteOperationRequest); /** DeleteOperationRequest name. */ public name: string; /** * Creates a new DeleteOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns DeleteOperationRequest instance */ public static create(properties?: google.longrunning.IDeleteOperationRequest): google.longrunning.DeleteOperationRequest; /** * Encodes the specified DeleteOperationRequest message. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages. * @param message DeleteOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.longrunning.IDeleteOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified DeleteOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.DeleteOperationRequest.verify|verify} messages. * @param message DeleteOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.longrunning.IDeleteOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DeleteOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns DeleteOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.DeleteOperationRequest; /** * Decodes a DeleteOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns DeleteOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.DeleteOperationRequest; /** * Verifies a DeleteOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a DeleteOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns DeleteOperationRequest */ public static fromObject(object: { [k: string]: any }): google.longrunning.DeleteOperationRequest; /** * Creates a plain object from a DeleteOperationRequest message. Also converts values to other types if specified. * @param message DeleteOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.longrunning.DeleteOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DeleteOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a WaitOperationRequest. */ interface IWaitOperationRequest { /** WaitOperationRequest name */ name?: (string|null); /** WaitOperationRequest timeout */ timeout?: (google.protobuf.IDuration|null); } /** Represents a WaitOperationRequest. */ class WaitOperationRequest implements IWaitOperationRequest { /** * Constructs a new WaitOperationRequest. * @param [properties] Properties to set */ constructor(properties?: google.longrunning.IWaitOperationRequest); /** WaitOperationRequest name. */ public name: string; /** WaitOperationRequest timeout. */ public timeout?: (google.protobuf.IDuration|null); /** * Creates a new WaitOperationRequest instance using the specified properties. * @param [properties] Properties to set * @returns WaitOperationRequest instance */ public static create(properties?: google.longrunning.IWaitOperationRequest): google.longrunning.WaitOperationRequest; /** * Encodes the specified WaitOperationRequest message. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages. * @param message WaitOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.longrunning.IWaitOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified WaitOperationRequest message, length delimited. Does not implicitly {@link google.longrunning.WaitOperationRequest.verify|verify} messages. * @param message WaitOperationRequest message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.longrunning.IWaitOperationRequest, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a WaitOperationRequest message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns WaitOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.WaitOperationRequest; /** * Decodes a WaitOperationRequest message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns WaitOperationRequest * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.WaitOperationRequest; /** * Verifies a WaitOperationRequest message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a WaitOperationRequest message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns WaitOperationRequest */ public static fromObject(object: { [k: string]: any }): google.longrunning.WaitOperationRequest; /** * Creates a plain object from a WaitOperationRequest message. Also converts values to other types if specified. * @param message WaitOperationRequest * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.longrunning.WaitOperationRequest, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this WaitOperationRequest to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an OperationInfo. */ interface IOperationInfo { /** OperationInfo responseType */ responseType?: (string|null); /** OperationInfo metadataType */ metadataType?: (string|null); } /** Represents an OperationInfo. */ class OperationInfo implements IOperationInfo { /** * Constructs a new OperationInfo. * @param [properties] Properties to set */ constructor(properties?: google.longrunning.IOperationInfo); /** OperationInfo responseType. */ public responseType: string; /** OperationInfo metadataType. */ public metadataType: string; /** * Creates a new OperationInfo instance using the specified properties. * @param [properties] Properties to set * @returns OperationInfo instance */ public static create(properties?: google.longrunning.IOperationInfo): google.longrunning.OperationInfo; /** * Encodes the specified OperationInfo message. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages. * @param message OperationInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: google.longrunning.IOperationInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified OperationInfo message, length delimited. Does not implicitly {@link google.longrunning.OperationInfo.verify|verify} messages. * @param message OperationInfo message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: google.longrunning.IOperationInfo, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an OperationInfo message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns OperationInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.longrunning.OperationInfo; /** * Decodes an OperationInfo message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns OperationInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.longrunning.OperationInfo; /** * Verifies an OperationInfo message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an OperationInfo message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns OperationInfo */ public static fromObject(object: { [k: string]: any }): google.longrunning.OperationInfo; /** * Creates a plain object from an OperationInfo message. Also converts values to other types if specified. * @param message OperationInfo * @param [options] Conversion options * @returns Plain object */ public static toObject(message: google.longrunning.OperationInfo, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this OperationInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } }
PartialResultSet
index.js
import React from "react"; import debug from "debug"; import { ApolloConsumer } from "react-apollo"; import MainLayout from "../layouts/MainLayout"; import IndexView from "./index_.jsx"; const log = debug("app:index"); class IndexPage extends React.Component { handleClick(event, client) { log("event: ", event.target.id); } /** * Render the component. */ render() { return (
</MainLayout> )} </ApolloConsumer> ); } } export default IndexPage;
<ApolloConsumer> {client => ( <MainLayout apolloClient={client}> <IndexView onHandleClick={e => this.handleClick(e, client)} />
store.js
import { createStore, applyMiddleware } from 'redux' import { composeWithDevTools } from 'redux-devtools-extension' import thunkMiddleware from 'redux-thunk' import reducer from './rootReducer' const exampleInitialState = { count: 0 } export function
(initialState = exampleInitialState) { return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunkMiddleware))) }
initializeStore
application.go
package sdk import ( "encoding/json" "fmt" "net/http" "net/url" "time" ) // Repository structs contains all needed information about a single repository type Repository struct { URL string Hook bool } // Application represent an application in a project type Application struct { ID int64 `json:"id" db:"id"` Name string `json:"name" db:"name" cli:"name,key"` Description string `json:"description" db:"description"` ProjectID int64 `json:"-" db:"project_id"` ProjectKey string `json:"project_key" db:"-"` ApplicationGroups []GroupPermission `json:"groups,omitempty" db:"-"` Variable []Variable `json:"variables,omitempty" db:"-"` Pipelines []ApplicationPipeline `json:"pipelines,omitempty" db:"-"` PipelinesBuild []PipelineBuild `json:"pipelines_build,omitempty" db:"-"` Permission int `json:"permission" db:"-"` Notifications []UserNotification `json:"notifications,omitempty" db:"-"` LastModified time.Time `json:"last_modified" db:"last_modified"` VCSServer string `json:"vcs_server,omitempty" db:"vcs_server"` RepositoryFullname string `json:"repository_fullname,omitempty" db:"repo_fullname"` RepositoryPollers []RepositoryPoller `json:"pollers,omitempty" db:"-"` RepositoryStrategy RepositoryStrategy `json:"vcs_strategy,omitempty" db:"-"` Hooks []Hook `json:"hooks,omitempty" db:"-"` Workflows []CDPipeline `json:"workflows,omitempty" db:"-"` Schedulers []PipelineScheduler `json:"schedulers,omitempty" db:"-"` Metadata Metadata `json:"metadata" yaml:"metadata" db:"-"` WorkflowMigration string `json:"workflow_migration" yaml:"workflow_migration" db:"workflow_migration"` Keys []ApplicationKey `json:"keys" yaml:"keys" db:"-"` Usage *Usage `json:"usage,omitempty" db:"-" cli:"-"` } // RepositoryStrategy represent the way to use the repository type RepositoryStrategy struct { ConnectionType string `json:"connection_type"` SSHKey string `json:"ssh_key"` User string `json:"user"` Password string `json:"password"` Branch string `json:"branch"` DefaultBranch string `json:"default_branch"` PGPKey string `json:"pgp_key"` } // ApplicationVariableAudit represents an audit on an application variable type ApplicationVariableAudit struct { ID int64 `json:"id" yaml:"-" db:"id"` ApplicationID int64 `json:"application_id" yaml:"-" db:"application_id"` VariableID int64 `json:"variable_id" yaml:"-" db:"variable_id"` Type string `json:"type" yaml:"-" db:"type"` VariableBefore *Variable `json:"variable_before,omitempty" yaml:"-" db:"-"` VariableAfter *Variable `json:"variable_after,omitempty" yaml:"-" db:"-"` Versionned time.Time `json:"versionned" yaml:"-" db:"versionned"` Author string `json:"author" yaml:"-" db:"author"` } // ApplicationPipeline Represent the link between an application and a pipeline type ApplicationPipeline struct { ID int64 `json:"id"` Pipeline Pipeline `json:"pipeline"` Parameters []Parameter `json:"parameters"` LastModified int64 `json:"last_modified"` Triggers []PipelineTrigger `json:"triggers,omitempty"` } // NewApplication instanciate a new NewApplication func NewApplication(name string) *Application { a := &Application{ Name: name, } return a } // AddApplication create an application in the given project func AddApplication(key, appName string) error { a := NewApplication(appName) data, err := json.Marshal(a) if err != nil { return err } url := fmt.Sprintf("/project/%s/applications", key) data, _, err = Request("POST", url, data) if err != nil { return err } return DecodeError(data) } // ListApplications returns all available application for the given project func ListApplications(key string) ([]Application, error) { url := fmt.Sprintf("/project/%s/applications", key) data, _, err := Request("GET", url, nil) if err != nil { return nil, err } var applications []Application if err := json.Unmarshal(data, &applications); err != nil { return nil, err } return applications, nil } // GetApplicationOptions are options for GetApplication var GetApplicationOptions = struct { WithPollers RequestModifier WithHooks RequestModifier WithNotifs RequestModifier WithWorkflow RequestModifier WithTriggers RequestModifier WithSchedulers RequestModifier }{ WithPollers: func(r *http.Request) { q := r.URL.Query() q.Set("withPollers", "true") r.URL.RawQuery = q.Encode() }, WithHooks: func(r *http.Request) { q := r.URL.Query() q.Set("withHooks", "true") r.URL.RawQuery = q.Encode() }, WithNotifs: func(r *http.Request) { q := r.URL.Query() q.Set("withNotifs", "true") r.URL.RawQuery = q.Encode() }, WithWorkflow: func(r *http.Request) { q := r.URL.Query() q.Set("withWorkflow", "true") r.URL.RawQuery = q.Encode() }, WithTriggers: func(r *http.Request) { q := r.URL.Query() q.Set("withTriggers", "true") r.URL.RawQuery = q.Encode() }, WithSchedulers: func(r *http.Request) { q := r.URL.Query() q.Set("withSchedulers", "true") r.URL.RawQuery = q.Encode() }, } // GetApplication retrieve the given application from CDS func GetApplication(pk, name string, opts ...RequestModifier) (*Application, error) { var a Application path := fmt.Sprintf("/project/%s/application/%s", pk, name) data, _, err := Request("GET", path, nil, opts...) if err != nil { return nil, err } if err := json.Unmarshal(data, &a); err != nil { return nil, err } return &a, nil } // UpdateApplication update an application in CDS func UpdateApplication(app *Application) error { data, err := json.Marshal(app) if err != nil { return err } url := fmt.Sprintf("/project/%s/application/%s", app.ProjectKey, app.Name) data, _, err = Request("PUT", url, data) if err != nil { return err } return DecodeError(data) } // RenameApplication renames an application from CDS func RenameApplication(pk, name, newName string) error { app := NewApplication(newName) data, err := json.Marshal(app) if err != nil { return err } url := fmt.Sprintf("/project/%s/application/%s", pk, name) data, _, err = Request("PUT", url, data) if err != nil { return err } return DecodeError(data) } // DeleteApplication delete an application from CDS func DeleteApplication(pk, name string) error { path := fmt.Sprintf("/project/%s/application/%s", pk, name) _, _, err := Request("DELETE", path, nil) return err } // ShowApplicationVariable show variables for an application func ShowApplicationVariable(projectKey, appName string) ([]Variable, error)
// AddApplicationVariable add a variable in an application func AddApplicationVariable(projectKey, appName, varName, varValue string, varType string) error { newVar := Variable{ Name: varName, Value: varValue, Type: varType, } data, err := json.Marshal(newVar) if err != nil { return err } path := fmt.Sprintf("/project/%s/application/%s/variable/%s", projectKey, appName, varName) data, _, err = Request("POST", path, data) if err != nil { return err } return DecodeError(data) } // GetVariableInApplication Get a variable in the given application func GetVariableInApplication(projectKey, appName, name string) (*Variable, error) { var v Variable path := fmt.Sprintf("/project/%s/application/%s/variable/%s", projectKey, appName, name) data, _, err := Request("GET", path, nil) if err != nil { return nil, err } if e := DecodeError(data); e != nil { return nil, e } if err := json.Unmarshal(data, &v); err != nil { return nil, err } return &v, nil } // UpdateApplicationVariable update a variable in an application func UpdateApplicationVariable(projectKey, appName, oldName, varName, varValue, varType string) error { oldVar, err := GetVariableInApplication(projectKey, appName, oldName) if err != nil { return err } newVar := Variable{ ID: oldVar.ID, Name: varName, Value: varValue, Type: varType, } data, err := json.Marshal(newVar) if err != nil { return err } path := fmt.Sprintf("/project/%s/application/%s/variable/%s", projectKey, appName, varName) data, _, err = Request("PUT", path, data) if err != nil { return err } return DecodeError(data) } // RemoveApplicationVariable remove a variable from an application func RemoveApplicationVariable(projectKey, appName, varName string) error { path := fmt.Sprintf("/project/%s/application/%s/variable/%s", projectKey, appName, varName) data, _, err := Request("DELETE", path, nil) if err != nil { return err } return DecodeError(data) } // RemoveGroupFromApplication call api to remove a group from the given application func RemoveGroupFromApplication(projectKey, appName, groupName string) error { path := fmt.Sprintf("/project/%s/application/%s/group/%s", projectKey, appName, groupName) data, _, err := Request("DELETE", path, nil) if err != nil { return err } return DecodeError(data) } // UpdateGroupInApplication call api to update group permission for the given application func UpdateGroupInApplication(projectKey, appName, groupName string, permission int) error { if permission < 4 || permission > 7 { return fmt.Errorf("Permission should be between 4-7") } groupApplication := GroupPermission{ Group: Group{ Name: groupName, }, Permission: permission, } data, err := json.Marshal(groupApplication) if err != nil { return err } path := fmt.Sprintf("/project/%s/application/%s/group/%s", projectKey, appName, groupName) data, _, err = Request("PUT", path, data) if err != nil { return err } return DecodeError(data) } // AddGroupInApplication add a group in an application func AddGroupInApplication(projectKey, appName, groupName string, permission int) error { if permission < 4 || permission > 7 { return fmt.Errorf("Permission should be between 4-7 ") } groupPipeline := GroupPermission{ Group: Group{ Name: groupName, }, Permission: permission, } data, err := json.Marshal(groupPipeline) if err != nil { return err } path := fmt.Sprintf("/project/%s/application/%s/group", projectKey, appName) data, _, err = Request("POST", path, data) if err != nil { return err } return DecodeError(data) } // ListApplicationPipeline list all pipelines attached to the application func ListApplicationPipeline(projectKey, appName string) ([]Pipeline, error) { var pipelines []Pipeline path := fmt.Sprintf("/project/%s/application/%s/pipeline", projectKey, appName) data, _, errReq := Request("GET", path, nil) if errReq != nil { return nil, errReq } if e := DecodeError(data); e != nil { return nil, e } if err := json.Unmarshal(data, &pipelines); err != nil { return nil, err } for i, pip := range pipelines { pip2, err := GetPipeline(projectKey, pip.Name) if err != nil { return nil, err } pipelines[i] = *pip2 } return pipelines, nil } // AttachPipeline allows pipeline to be used in application context func AttachPipeline(key, app, pip string) error { return AddApplicationPipeline(key, app, pip) } // AddApplicationPipeline add a pipeline in an application func AddApplicationPipeline(projectKey, appName, pipelineName string) error { path := fmt.Sprintf("/project/%s/application/%s/pipeline/%s", projectKey, appName, pipelineName) data, _, err := Request("POST", path, nil) if err != nil { return err } return DecodeError(data) } // UpdateApplicationPipeline add a pipeline in an application func UpdateApplicationPipeline(projectKey, appName, pipelineName string, params []Parameter) error { data, err := json.Marshal(params) if err != nil { return err } path := fmt.Sprintf("/project/%s/application/%s/pipeline/%s", projectKey, appName, pipelineName) data, _, err = Request("PUT", path, data) if err != nil { return err } return DecodeError(data) } // RemoveApplicationPipeline remove a pipeline from an application func RemoveApplicationPipeline(projectKey, appName, pipelineName string) error { path := fmt.Sprintf("/project/%s/application/%s/pipeline/%s", projectKey, appName, pipelineName) data, _, err := Request("DELETE", path, nil) if err != nil { return err } return DecodeError(data) } //GetPipelineScheduler returns all pipeline scheduler func GetPipelineScheduler(projectKey, appName, pipelineName string) ([]PipelineScheduler, error) { path := fmt.Sprintf("/project/%s/application/%s/pipeline/%s/scheduler", projectKey, appName, pipelineName) data, _, err := Request("GET", path, nil) if err != nil { return nil, err } if err := DecodeError(data); err != nil { return nil, err } ps := []PipelineScheduler{} if err := json.Unmarshal(data, &ps); err != nil { return nil, err } return ps, nil } //AddPipelineScheduler add a pipeline scheduler func AddPipelineScheduler(projectKey, appName, pipelineName, cronExpr, envName string, params []Parameter) (*PipelineScheduler, error) { s := PipelineScheduler{ Crontab: cronExpr, Args: params, } b, err := json.Marshal(s) if err != nil { return nil, err } path := fmt.Sprintf("/project/%s/application/%s/pipeline/%s/scheduler", projectKey, appName, pipelineName) if envName != "" { path = path + "?envName=" + url.QueryEscape(envName) } data, _, err := Request("POST", path, b) if err != nil { return nil, err } if err := DecodeError(data); err != nil { return nil, err } if err := json.Unmarshal(data, &s); err != nil { return nil, err } return &s, nil } //UpdatePipelineScheduler update a pipeline scheduler func UpdatePipelineScheduler(projectKey, appName, pipelineName string, s *PipelineScheduler) (*PipelineScheduler, error) { b, err := json.Marshal(s) if err != nil { return nil, err } path := fmt.Sprintf("/project/%s/application/%s/pipeline/%s/scheduler", projectKey, appName, pipelineName) data, _, err := Request("PUT", path, b) if err != nil { return nil, err } if err := DecodeError(data); err != nil { return nil, err } if err := json.Unmarshal(data, s); err != nil { return nil, err } return s, nil } //DeletePipelineScheduler update a pipeline scheduler func DeletePipelineScheduler(projectKey, appName, pipelineName string, s *PipelineScheduler) error { path := fmt.Sprintf("/project/%s/application/%s/pipeline/%s/scheduler/%d", projectKey, appName, pipelineName, s.ID) data, _, err := Request("DELETE", path, nil) if err != nil { return err } return DecodeError(data) }
{ path := fmt.Sprintf("/project/%s/application/%s/variable", projectKey, appName) data, _, err := Request("GET", path, nil) if err != nil { return nil, err } var variables []Variable if err := json.Unmarshal(data, &variables); err != nil { return nil, err } return variables, nil }
common.go
package serializer import "github.com/gin-gonic/gin" // Response 基础序列化器 type Response struct { Code int `json:"code"` Data interface{} `json:"data,omitempty"` Msg string `json:"msg"` Error string `json:"error,omitempty"` } // TrackedErrorResponse 有追踪信息的错误响应 type TrackedErrorResponse struct { Response TrackID string `json:"track_id"` } // 三位数错误编码为复用http原本含义 // 五位数错误编码为应用自定义错误 // 五开头的五位数错误编码为服务器端错误,比如数据库操作失败 // 四开头的五位数错误编码为客户端错误,有时候是客户端代码写错了,有时候是用户操作错误 const ( // CodeCheckLogin 未登录 CodeCheckLogin = 401 // CodeNoRightErr 未授权访问 CodeNoRightErr = 403 // CodeDBError 数据库操作失败 CodeDBError = 50001 // CodeEncryptError 加密失败 CodeEncryptError = 50002 //CodeParamErr 各种奇奇怪怪的参数错误 CodeParamErr = 40001 ) // CheckLogin 检查登录 func CheckLogin() Response { return Response{ Code: CodeCheckLogin, Msg: "未登录", } } // Err 通用错误处理 func Err(errCode int, msg string, err error) Response { res := Response{ Code: errCode, Msg: msg, } // 生产环境隐藏底层报错 if err != nil && gin.Mode() != gin.ReleaseMode { res.Error = err.Error() } return res } // DBErr 数据库操作失败 func DBErr(msg string, err error) Response { if msg == "" { msg = "数据库操作失败" } return Err(CodeDBError, msg, err) } // ParamErr 各种参数错误 func ParamErr(msg string, err error) Response { if msg == "" { msg = "参数错误" } return Err(CodeParamErr, msg, err) } // DataList 基础列表结构 type DataList struct { Items interface{} `json:"items"` Total uint `json:"total"` } // BuildListResponse 列表构建器 func BuildListResponse(items interface{}, total uint) Response { return Response{ Data: DataList{ Items: items, Total: total, }, } }
AggregateUsersInConversationsArgs.ts
import * as TypeGraphQL from "type-graphql"; import * as GraphQLScalars from "graphql-scalars"; import { UsersInConversationsOrderByWithRelationInput } from "../../../inputs/UsersInConversationsOrderByWithRelationInput"; import { UsersInConversationsWhereInput } from "../../../inputs/UsersInConversationsWhereInput"; import { UsersInConversationsWhereUniqueInput } from "../../../inputs/UsersInConversationsWhereUniqueInput"; @TypeGraphQL.ArgsType() export class AggregateUsersInConversationsArgs { @TypeGraphQL.Field(_type => UsersInConversationsWhereInput, { nullable: true }) where?: UsersInConversationsWhereInput | undefined; @TypeGraphQL.Field(_type => [UsersInConversationsOrderByWithRelationInput], { nullable: true }) orderBy?: UsersInConversationsOrderByWithRelationInput[] | undefined; @TypeGraphQL.Field(_type => UsersInConversationsWhereUniqueInput, { nullable: true }) cursor?: UsersInConversationsWhereUniqueInput | undefined; @TypeGraphQL.Field(_type => TypeGraphQL.Int, { nullable: true }) take?: number | undefined; @TypeGraphQL.Field(_type => TypeGraphQL.Int, { nullable: true }) skip?: number | undefined;
}
slice-init.rs
// compile-flags: -C no-prepopulate-passes #![crate_type = "lib"] // CHECK-LABEL: @zero_sized_elem #[no_mangle] pub fn zero_sized_elem() { // CHECK-NOT: br label %repeat_loop_header{{.*}} // CHECK-NOT: call void @llvm.memset.p0 let x = [(); 4]; drop(&x); } // CHECK-LABEL: @zero_len_array #[no_mangle]
// CHECK-NOT: br label %repeat_loop_header{{.*}} // CHECK-NOT: call void @llvm.memset.p0 let x = [4; 0]; drop(&x); } // CHECK-LABEL: @byte_array #[no_mangle] pub fn byte_array() { // CHECK: call void @llvm.memset.{{.+}}({{i8\*|ptr}} {{.*}}, i8 7, i{{[0-9]+}} 4 // CHECK-NOT: br label %repeat_loop_header{{.*}} let x = [7u8; 4]; drop(&x); } #[allow(dead_code)] #[derive(Copy, Clone)] enum Init { Loop, Memset, } // CHECK-LABEL: @byte_enum_array #[no_mangle] pub fn byte_enum_array() { // CHECK: call void @llvm.memset.{{.+}}({{i8\*|ptr}} {{.*}}, i8 {{.*}}, i{{[0-9]+}} 4 // CHECK-NOT: br label %repeat_loop_header{{.*}} let x = [Init::Memset; 4]; drop(&x); } // CHECK-LABEL: @zeroed_integer_array #[no_mangle] pub fn zeroed_integer_array() { // CHECK: call void @llvm.memset.{{.+}}({{i8\*|ptr}} {{.*}}, i8 0, i{{[0-9]+}} 16 // CHECK-NOT: br label %repeat_loop_header{{.*}} let x = [0u32; 4]; drop(&x); } // CHECK-LABEL: @nonzero_integer_array #[no_mangle] pub fn nonzero_integer_array() { // CHECK: br label %repeat_loop_header{{.*}} // CHECK-NOT: call void @llvm.memset.p0 let x = [0x1a_2b_3c_4d_u32; 4]; drop(&x); }
pub fn zero_len_array() {
test_base.py
# -*- coding: utf-8 -*- from __future__ import print_function import re import sys from datetime import datetime, timedelta import numpy as np import pandas as pd import pandas.compat as compat from pandas.types.common import (is_object_dtype, is_datetimetz, needs_i8_conversion) import pandas.util.testing as tm from pandas import (Series, Index, DatetimeIndex, TimedeltaIndex, PeriodIndex, Timedelta) from pandas.compat import u, StringIO from pandas.compat.numpy import np_array_datetime64_compat from pandas.core.base import (FrozenList, FrozenNDArray, PandasDelegate, NoNewAttributesMixin) from pandas.tseries.base import DatetimeIndexOpsMixin class CheckStringMixin(object): def test_string_methods_dont_fail(self): repr(self.container) str(self.container) bytes(self.container) if not compat.PY3: unicode(self.container) # noqa def test_tricky_container(self): if not hasattr(self, 'unicode_container'): raise nose.SkipTest('Need unicode_container to test with this') repr(self.unicode_container) str(self.unicode_container) bytes(self.unicode_container) if not compat.PY3: unicode(self.unicode_container) # noqa class CheckImmutable(object): mutable_regex = re.compile('does not support mutable operations') def check_mutable_error(self, *args, **kwargs): # pass whatever functions you normally would to assertRaises (after the # Exception kind) tm.assertRaisesRegexp(TypeError, self.mutable_regex, *args, **kwargs) def test_no_mutable_funcs(self): def setitem(): self.container[0] = 5 self.check_mutable_error(setitem) def setslice(): self.container[1:2] = 3 self.check_mutable_error(setslice) def delitem(): del self.container[0] self.check_mutable_error(delitem) def delslice(): del self.container[0:3] self.check_mutable_error(delslice) mutable_methods = getattr(self, "mutable_methods", []) for meth in mutable_methods: self.check_mutable_error(getattr(self.container, meth)) def test_slicing_maintains_type(self): result = self.container[1:2] expected = self.lst[1:2] self.check_result(result, expected) def check_result(self, result, expected, klass=None): klass = klass or self.klass self.assertIsInstance(result, klass) self.assertEqual(result, expected) class TestFrozenList(CheckImmutable, CheckStringMixin, tm.TestCase): mutable_methods = ('extend', 'pop', 'remove', 'insert') unicode_container = FrozenList([u("\u05d0"), u("\u05d1"), "c"]) def setUp(self): self.lst = [1, 2, 3, 4, 5] self.container = FrozenList(self.lst) self.klass = FrozenList def test_add(self): result = self.container + (1, 2, 3) expected = FrozenList(self.lst + [1, 2, 3]) self.check_result(result, expected) result = (1, 2, 3) + self.container expected = FrozenList([1, 2, 3] + self.lst) self.check_result(result, expected) def test_inplace(self): q = r = self.container q += [5] self.check_result(q, self.lst + [5]) # other shouldn't be mutated self.check_result(r, self.lst) class TestFrozenNDArray(CheckImmutable, CheckStringMixin, tm.TestCase): mutable_methods = ('put', 'itemset', 'fill') unicode_container = FrozenNDArray([u("\u05d0"), u("\u05d1"), "c"]) def setUp(self): self.lst = [3, 5, 7, -2] self.container = FrozenNDArray(self.lst) self.klass = FrozenNDArray def test_shallow_copying(self): original = self.container.copy() self.assertIsInstance(self.container.view(), FrozenNDArray) self.assertFalse(isinstance( self.container.view(np.ndarray), FrozenNDArray)) self.assertIsNot(self.container.view(), self.container) self.assert_numpy_array_equal(self.container, original) # shallow copy should be the same too self.assertIsInstance(self.container._shallow_copy(), FrozenNDArray) # setting should not be allowed def testit(container): container[0] = 16 self.check_mutable_error(testit, self.container) def test_values(self): original = self.container.view(np.ndarray).copy() n = original[0] + 15 vals = self.container.values() self.assert_numpy_array_equal(original, vals) self.assertIsNot(original, vals) vals[0] = n self.assertIsInstance(self.container, pd.core.base.FrozenNDArray) self.assert_numpy_array_equal(self.container.values(), original) self.assertEqual(vals[0], n) class TestPandasDelegate(tm.TestCase): class Delegator(object): _properties = ['foo'] _methods = ['bar'] def _set_foo(self, value): self.foo = value def _get_foo(self): return self.foo foo = property(_get_foo, _set_foo, doc="foo property") def bar(self, *args, **kwargs): """ a test bar method """ pass class Delegate(PandasDelegate): def __init__(self, obj): self.obj = obj def setUp(self):
def test_invalida_delgation(self): # these show that in order for the delegation to work # the _delegate_* methods need to be overriden to not raise a TypeError self.Delegate._add_delegate_accessors( delegate=self.Delegator, accessors=self.Delegator._properties, typ='property' ) self.Delegate._add_delegate_accessors( delegate=self.Delegator, accessors=self.Delegator._methods, typ='method' ) delegate = self.Delegate(self.Delegator()) def f(): delegate.foo self.assertRaises(TypeError, f) def f(): delegate.foo = 5 self.assertRaises(TypeError, f) def f(): delegate.foo() self.assertRaises(TypeError, f) def test_memory_usage(self): # Delegate does not implement memory_usage. # Check that we fall back to in-built `__sizeof__` # GH 12924 delegate = self.Delegate(self.Delegator()) sys.getsizeof(delegate) class Ops(tm.TestCase): def _allow_na_ops(self, obj): """Whether to skip test cases including NaN""" if (isinstance(obj, Index) and (obj.is_boolean() or not obj._can_hold_na)): # don't test boolean / int64 index return False return True def setUp(self): self.bool_index = tm.makeBoolIndex(10, name='a') self.int_index = tm.makeIntIndex(10, name='a') self.float_index = tm.makeFloatIndex(10, name='a') self.dt_index = tm.makeDateIndex(10, name='a') self.dt_tz_index = tm.makeDateIndex(10, name='a').tz_localize( tz='US/Eastern') self.period_index = tm.makePeriodIndex(10, name='a') self.string_index = tm.makeStringIndex(10, name='a') self.unicode_index = tm.makeUnicodeIndex(10, name='a') arr = np.random.randn(10) self.int_series = Series(arr, index=self.int_index, name='a') self.float_series = Series(arr, index=self.float_index, name='a') self.dt_series = Series(arr, index=self.dt_index, name='a') self.dt_tz_series = self.dt_tz_index.to_series(keep_tz=True) self.period_series = Series(arr, index=self.period_index, name='a') self.string_series = Series(arr, index=self.string_index, name='a') types = ['bool', 'int', 'float', 'dt', 'dt_tz', 'period', 'string', 'unicode'] fmts = ["{0}_{1}".format(t, f) for t in types for f in ['index', 'series']] self.objs = [getattr(self, f) for f in fmts if getattr(self, f, None) is not None] def check_ops_properties(self, props, filter=None, ignore_failures=False): for op in props: for o in self.is_valid_objs: # if a filter, skip if it doesn't match if filter is not None: filt = o.index if isinstance(o, Series) else o if not filter(filt): continue try: if isinstance(o, Series): expected = Series( getattr(o.index, op), index=o.index, name='a') else: expected = getattr(o, op) except (AttributeError): if ignore_failures: continue result = getattr(o, op) # these couuld be series, arrays or scalars if isinstance(result, Series) and isinstance(expected, Series): tm.assert_series_equal(result, expected) elif isinstance(result, Index) and isinstance(expected, Index): tm.assert_index_equal(result, expected) elif isinstance(result, np.ndarray) and isinstance(expected, np.ndarray): self.assert_numpy_array_equal(result, expected) else: self.assertEqual(result, expected) # freq raises AttributeError on an Int64Index because its not # defined we mostly care about Series hwere anyhow if not ignore_failures: for o in self.not_valid_objs: # an object that is datetimelike will raise a TypeError, # otherwise an AttributeError if issubclass(type(o), DatetimeIndexOpsMixin): self.assertRaises(TypeError, lambda: getattr(o, op)) else: self.assertRaises(AttributeError, lambda: getattr(o, op)) def test_binary_ops_docs(self): from pandas import DataFrame, Panel op_map = {'add': '+', 'sub': '-', 'mul': '*', 'mod': '%', 'pow': '**', 'truediv': '/', 'floordiv': '//'} for op_name in ['add', 'sub', 'mul', 'mod', 'pow', 'truediv', 'floordiv']: for klass in [Series, DataFrame, Panel]: operand1 = klass.__name__.lower() operand2 = 'other' op = op_map[op_name] expected_str = ' '.join([operand1, op, operand2]) self.assertTrue(expected_str in getattr(klass, op_name).__doc__) # reverse version of the binary ops expected_str = ' '.join([operand2, op, operand1]) self.assertTrue(expected_str in getattr(klass, 'r' + op_name).__doc__) class TestIndexOps(Ops): def setUp(self): super(TestIndexOps, self).setUp() self.is_valid_objs = [o for o in self.objs if o._allow_index_ops] self.not_valid_objs = [o for o in self.objs if not o._allow_index_ops] def test_none_comparison(self): # bug brought up by #1079 # changed from TypeError in 0.17.0 for o in self.is_valid_objs: if isinstance(o, Series): o[0] = np.nan # noinspection PyComparisonWithNone result = o == None # noqa self.assertFalse(result.iat[0]) self.assertFalse(result.iat[1]) # noinspection PyComparisonWithNone result = o != None # noqa self.assertTrue(result.iat[0]) self.assertTrue(result.iat[1]) result = None == o # noqa self.assertFalse(result.iat[0]) self.assertFalse(result.iat[1]) # this fails for numpy < 1.9 # and oddly for *some* platforms # result = None != o # noqa # self.assertTrue(result.iat[0]) # self.assertTrue(result.iat[1]) result = None > o self.assertFalse(result.iat[0]) self.assertFalse(result.iat[1]) result = o < None self.assertFalse(result.iat[0]) self.assertFalse(result.iat[1]) def test_ndarray_compat_properties(self): for o in self.objs: # check that we work for p in ['shape', 'dtype', 'flags', 'T', 'strides', 'itemsize', 'nbytes']: self.assertIsNotNone(getattr(o, p, None)) self.assertTrue(hasattr(o, 'base')) # if we have a datetimelike dtype then needs a view to work # but the user is responsible for that try: self.assertIsNotNone(o.data) except ValueError: pass self.assertRaises(ValueError, o.item) # len > 1 self.assertEqual(o.ndim, 1) self.assertEqual(o.size, len(o)) self.assertEqual(Index([1]).item(), 1) self.assertEqual(Series([1]).item(), 1) def test_ops(self): for op in ['max', 'min']: for o in self.objs: result = getattr(o, op)() if not isinstance(o, PeriodIndex): expected = getattr(o.values, op)() else: expected = pd.Period(ordinal=getattr(o._values, op)(), freq=o.freq) try: self.assertEqual(result, expected) except TypeError: # comparing tz-aware series with np.array results in # TypeError expected = expected.astype('M8[ns]').astype('int64') self.assertEqual(result.value, expected) def test_nanops(self): # GH 7261 for op in ['max', 'min']: for klass in [Index, Series]: obj = klass([np.nan, 2.0]) self.assertEqual(getattr(obj, op)(), 2.0) obj = klass([np.nan]) self.assertTrue(pd.isnull(getattr(obj, op)())) obj = klass([]) self.assertTrue(pd.isnull(getattr(obj, op)())) obj = klass([pd.NaT, datetime(2011, 11, 1)]) # check DatetimeIndex monotonic path self.assertEqual(getattr(obj, op)(), datetime(2011, 11, 1)) obj = klass([pd.NaT, datetime(2011, 11, 1), pd.NaT]) # check DatetimeIndex non-monotonic path self.assertEqual(getattr(obj, op)(), datetime(2011, 11, 1)) # argmin/max obj = Index(np.arange(5, dtype='int64')) self.assertEqual(obj.argmin(), 0) self.assertEqual(obj.argmax(), 4) obj = Index([np.nan, 1, np.nan, 2]) self.assertEqual(obj.argmin(), 1) self.assertEqual(obj.argmax(), 3) obj = Index([np.nan]) self.assertEqual(obj.argmin(), -1) self.assertEqual(obj.argmax(), -1) obj = Index([pd.NaT, datetime(2011, 11, 1), datetime(2011, 11, 2), pd.NaT]) self.assertEqual(obj.argmin(), 1) self.assertEqual(obj.argmax(), 2) obj = Index([pd.NaT]) self.assertEqual(obj.argmin(), -1) self.assertEqual(obj.argmax(), -1) def test_value_counts_unique_nunique(self): for orig in self.objs: o = orig.copy() klass = type(o) values = o._values if isinstance(values, Index): # reset name not to affect latter process values.name = None # create repeated values, 'n'th element is repeated by n+1 times # skip boolean, because it only has 2 values at most if isinstance(o, Index) and o.is_boolean(): continue elif isinstance(o, Index): expected_index = pd.Index(o[::-1]) expected_index.name = None o = o.repeat(range(1, len(o) + 1)) o.name = 'a' else: expected_index = pd.Index(values[::-1]) idx = o.index.repeat(range(1, len(o) + 1)) rep = np.repeat(values, range(1, len(o) + 1)) o = klass(rep, index=idx, name='a') # check values has the same dtype as the original self.assertEqual(o.dtype, orig.dtype) expected_s = Series(range(10, 0, -1), index=expected_index, dtype='int64', name='a') result = o.value_counts() tm.assert_series_equal(result, expected_s) self.assertTrue(result.index.name is None) self.assertEqual(result.name, 'a') result = o.unique() if isinstance(o, Index): self.assertTrue(isinstance(result, o.__class__)) self.assert_index_equal(result, orig) elif is_datetimetz(o): # datetimetz Series returns array of Timestamp self.assertEqual(result[0], orig[0]) for r in result: self.assertIsInstance(r, pd.Timestamp) tm.assert_numpy_array_equal(result, orig._values.asobject.values) else: tm.assert_numpy_array_equal(result, orig.values) self.assertEqual(o.nunique(), len(np.unique(o.values))) def test_value_counts_unique_nunique_null(self): for null_obj in [np.nan, None]: for orig in self.objs: o = orig.copy() klass = type(o) values = o._values if not self._allow_na_ops(o): continue # special assign to the numpy array if is_datetimetz(o): if isinstance(o, DatetimeIndex): v = o.asi8 v[0:2] = pd.tslib.iNaT values = o._shallow_copy(v) else: o = o.copy() o[0:2] = pd.tslib.iNaT values = o._values elif needs_i8_conversion(o): values[0:2] = pd.tslib.iNaT values = o._shallow_copy(values) else: values[0:2] = null_obj # check values has the same dtype as the original self.assertEqual(values.dtype, o.dtype) # create repeated values, 'n'th element is repeated by n+1 # times if isinstance(o, (DatetimeIndex, PeriodIndex)): expected_index = o.copy() expected_index.name = None # attach name to klass o = klass(values.repeat(range(1, len(o) + 1))) o.name = 'a' else: if is_datetimetz(o): expected_index = orig._values._shallow_copy(values) else: expected_index = pd.Index(values) expected_index.name = None o = o.repeat(range(1, len(o) + 1)) o.name = 'a' # check values has the same dtype as the original self.assertEqual(o.dtype, orig.dtype) # check values correctly have NaN nanloc = np.zeros(len(o), dtype=np.bool) nanloc[:3] = True if isinstance(o, Index): self.assert_numpy_array_equal(pd.isnull(o), nanloc) else: exp = pd.Series(nanloc, o.index, name='a') self.assert_series_equal(pd.isnull(o), exp) expected_s_na = Series(list(range(10, 2, -1)) + [3], index=expected_index[9:0:-1], dtype='int64', name='a') expected_s = Series(list(range(10, 2, -1)), index=expected_index[9:1:-1], dtype='int64', name='a') result_s_na = o.value_counts(dropna=False) tm.assert_series_equal(result_s_na, expected_s_na) self.assertTrue(result_s_na.index.name is None) self.assertEqual(result_s_na.name, 'a') result_s = o.value_counts() tm.assert_series_equal(o.value_counts(), expected_s) self.assertTrue(result_s.index.name is None) self.assertEqual(result_s.name, 'a') result = o.unique() if isinstance(o, Index): tm.assert_index_equal(result, Index(values[1:], name='a')) elif is_datetimetz(o): # unable to compare NaT / nan tm.assert_numpy_array_equal(result[1:], values[2:].asobject.values) self.assertIs(result[0], pd.NaT) else: tm.assert_numpy_array_equal(result[1:], values[2:]) self.assertTrue(pd.isnull(result[0])) self.assertEqual(result.dtype, orig.dtype) self.assertEqual(o.nunique(), 8) self.assertEqual(o.nunique(dropna=False), 9) def test_value_counts_inferred(self): klasses = [Index, Series] for klass in klasses: s_values = ['a', 'b', 'b', 'b', 'b', 'c', 'd', 'd', 'a', 'a'] s = klass(s_values) expected = Series([4, 3, 2, 1], index=['b', 'a', 'd', 'c']) tm.assert_series_equal(s.value_counts(), expected) if isinstance(s, Index): exp = Index(np.unique(np.array(s_values, dtype=np.object_))) tm.assert_index_equal(s.unique(), exp) else: exp = np.unique(np.array(s_values, dtype=np.object_)) tm.assert_numpy_array_equal(s.unique(), exp) self.assertEqual(s.nunique(), 4) # don't sort, have to sort after the fact as not sorting is # platform-dep hist = s.value_counts(sort=False).sort_values() expected = Series([3, 1, 4, 2], index=list('acbd')).sort_values() tm.assert_series_equal(hist, expected) # sort ascending hist = s.value_counts(ascending=True) expected = Series([1, 2, 3, 4], index=list('cdab')) tm.assert_series_equal(hist, expected) # relative histogram. hist = s.value_counts(normalize=True) expected = Series([.4, .3, .2, .1], index=['b', 'a', 'd', 'c']) tm.assert_series_equal(hist, expected) def test_value_counts_bins(self): klasses = [Index, Series] for klass in klasses: s_values = ['a', 'b', 'b', 'b', 'b', 'c', 'd', 'd', 'a', 'a'] s = klass(s_values) # bins self.assertRaises(TypeError, lambda bins: s.value_counts(bins=bins), 1) s1 = Series([1, 1, 2, 3]) res1 = s1.value_counts(bins=1) exp1 = Series({0.998: 4}) tm.assert_series_equal(res1, exp1) res1n = s1.value_counts(bins=1, normalize=True) exp1n = Series({0.998: 1.0}) tm.assert_series_equal(res1n, exp1n) if isinstance(s1, Index): tm.assert_index_equal(s1.unique(), Index([1, 2, 3])) else: exp = np.array([1, 2, 3], dtype=np.int64) tm.assert_numpy_array_equal(s1.unique(), exp) self.assertEqual(s1.nunique(), 3) res4 = s1.value_counts(bins=4) exp4 = Series({0.998: 2, 1.5: 1, 2.0: 0, 2.5: 1}, index=[0.998, 2.5, 1.5, 2.0]) tm.assert_series_equal(res4, exp4) res4n = s1.value_counts(bins=4, normalize=True) exp4n = Series( {0.998: 0.5, 1.5: 0.25, 2.0: 0.0, 2.5: 0.25}, index=[0.998, 2.5, 1.5, 2.0]) tm.assert_series_equal(res4n, exp4n) # handle NA's properly s_values = ['a', 'b', 'b', 'b', np.nan, np.nan, 'd', 'd', 'a', 'a', 'b'] s = klass(s_values) expected = Series([4, 3, 2], index=['b', 'a', 'd']) tm.assert_series_equal(s.value_counts(), expected) if isinstance(s, Index): exp = Index(['a', 'b', np.nan, 'd']) tm.assert_index_equal(s.unique(), exp) else: exp = np.array(['a', 'b', np.nan, 'd'], dtype=object) tm.assert_numpy_array_equal(s.unique(), exp) self.assertEqual(s.nunique(), 3) s = klass({}) expected = Series([], dtype=np.int64) tm.assert_series_equal(s.value_counts(), expected, check_index_type=False) # returned dtype differs depending on original if isinstance(s, Index): self.assert_index_equal(s.unique(), Index([]), exact=False) else: self.assert_numpy_array_equal(s.unique(), np.array([]), check_dtype=False) self.assertEqual(s.nunique(), 0) def test_value_counts_datetime64(self): klasses = [Index, Series] for klass in klasses: # GH 3002, datetime64[ns] # don't test names though txt = "\n".join(['xxyyzz20100101PIE', 'xxyyzz20100101GUM', 'xxyyzz20100101EGG', 'xxyyww20090101EGG', 'foofoo20080909PIE', 'foofoo20080909GUM']) f = StringIO(txt) df = pd.read_fwf(f, widths=[6, 8, 3], names=["person_id", "dt", "food"], parse_dates=["dt"]) s = klass(df['dt'].copy()) s.name = None idx = pd.to_datetime(['2010-01-01 00:00:00Z', '2008-09-09 00:00:00Z', '2009-01-01 00:00:00X']) expected_s = Series([3, 2, 1], index=idx) tm.assert_series_equal(s.value_counts(), expected_s) expected = np_array_datetime64_compat(['2010-01-01 00:00:00Z', '2009-01-01 00:00:00Z', '2008-09-09 00:00:00Z'], dtype='datetime64[ns]') if isinstance(s, Index): tm.assert_index_equal(s.unique(), DatetimeIndex(expected)) else: tm.assert_numpy_array_equal(s.unique(), expected) self.assertEqual(s.nunique(), 3) # with NaT s = df['dt'].copy() s = klass([v for v in s.values] + [pd.NaT]) result = s.value_counts() self.assertEqual(result.index.dtype, 'datetime64[ns]') tm.assert_series_equal(result, expected_s) result = s.value_counts(dropna=False) expected_s[pd.NaT] = 1 tm.assert_series_equal(result, expected_s) unique = s.unique() self.assertEqual(unique.dtype, 'datetime64[ns]') # numpy_array_equal cannot compare pd.NaT if isinstance(s, Index): exp_idx = DatetimeIndex(expected.tolist() + [pd.NaT]) tm.assert_index_equal(unique, exp_idx) else: tm.assert_numpy_array_equal(unique[:3], expected) self.assertTrue(pd.isnull(unique[3])) self.assertEqual(s.nunique(), 3) self.assertEqual(s.nunique(dropna=False), 4) # timedelta64[ns] td = df.dt - df.dt + timedelta(1) td = klass(td, name='dt') result = td.value_counts() expected_s = Series([6], index=[Timedelta('1day')], name='dt') tm.assert_series_equal(result, expected_s) expected = TimedeltaIndex(['1 days'], name='dt') if isinstance(td, Index): tm.assert_index_equal(td.unique(), expected) else: tm.assert_numpy_array_equal(td.unique(), expected.values) td2 = timedelta(1) + (df.dt - df.dt) td2 = klass(td2, name='dt') result2 = td2.value_counts() tm.assert_series_equal(result2, expected_s) def test_factorize(self): for orig in self.objs: o = orig.copy() if isinstance(o, Index) and o.is_boolean(): exp_arr = np.array([0, 1] + [0] * 8, dtype=np.intp) exp_uniques = o exp_uniques = Index([False, True]) else: exp_arr = np.array(range(len(o)), dtype=np.intp) exp_uniques = o labels, uniques = o.factorize() self.assert_numpy_array_equal(labels, exp_arr) if isinstance(o, Series): self.assert_index_equal(uniques, Index(orig), check_names=False) else: # factorize explicitly resets name self.assert_index_equal(uniques, exp_uniques, check_names=False) def test_factorize_repeated(self): for orig in self.objs: o = orig.copy() # don't test boolean if isinstance(o, Index) and o.is_boolean(): continue # sort by value, and create duplicates if isinstance(o, Series): o = o.sort_values() n = o.iloc[5:].append(o) else: indexer = o.argsort() o = o.take(indexer) n = o[5:].append(o) exp_arr = np.array([5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=np.intp) labels, uniques = n.factorize(sort=True) self.assert_numpy_array_equal(labels, exp_arr) if isinstance(o, Series): self.assert_index_equal(uniques, Index(orig).sort_values(), check_names=False) else: self.assert_index_equal(uniques, o, check_names=False) exp_arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4], np.intp) labels, uniques = n.factorize(sort=False) self.assert_numpy_array_equal(labels, exp_arr) if isinstance(o, Series): expected = Index(o.iloc[5:10].append(o.iloc[:5])) self.assert_index_equal(uniques, expected, check_names=False) else: expected = o[5:10].append(o[:5]) self.assert_index_equal(uniques, expected, check_names=False) def test_duplicated_drop_duplicates_index(self): # GH 4060 for original in self.objs: if isinstance(original, Index): # special case if original.is_boolean(): result = original.drop_duplicates() expected = Index([False, True], name='a') tm.assert_index_equal(result, expected) continue # original doesn't have duplicates expected = np.array([False] * len(original), dtype=bool) duplicated = original.duplicated() tm.assert_numpy_array_equal(duplicated, expected) self.assertTrue(duplicated.dtype == bool) result = original.drop_duplicates() tm.assert_index_equal(result, original) self.assertFalse(result is original) # has_duplicates self.assertFalse(original.has_duplicates) # create repeated values, 3rd and 5th values are duplicated idx = original[list(range(len(original))) + [5, 3]] expected = np.array([False] * len(original) + [True, True], dtype=bool) duplicated = idx.duplicated() tm.assert_numpy_array_equal(duplicated, expected) self.assertTrue(duplicated.dtype == bool) tm.assert_index_equal(idx.drop_duplicates(), original) base = [False] * len(idx) base[3] = True base[5] = True expected = np.array(base) duplicated = idx.duplicated(keep='last') tm.assert_numpy_array_equal(duplicated, expected) self.assertTrue(duplicated.dtype == bool) result = idx.drop_duplicates(keep='last') tm.assert_index_equal(result, idx[~expected]) # deprecate take_last with tm.assert_produces_warning(FutureWarning): duplicated = idx.duplicated(take_last=True) tm.assert_numpy_array_equal(duplicated, expected) self.assertTrue(duplicated.dtype == bool) with tm.assert_produces_warning(FutureWarning): result = idx.drop_duplicates(take_last=True) tm.assert_index_equal(result, idx[~expected]) base = [False] * len(original) + [True, True] base[3] = True base[5] = True expected = np.array(base) duplicated = idx.duplicated(keep=False) tm.assert_numpy_array_equal(duplicated, expected) self.assertTrue(duplicated.dtype == bool) result = idx.drop_duplicates(keep=False) tm.assert_index_equal(result, idx[~expected]) with tm.assertRaisesRegexp( TypeError, r"drop_duplicates\(\) got an unexpected " "keyword argument"): idx.drop_duplicates(inplace=True) else: expected = Series([False] * len(original), index=original.index, name='a') tm.assert_series_equal(original.duplicated(), expected) result = original.drop_duplicates() tm.assert_series_equal(result, original) self.assertFalse(result is original) idx = original.index[list(range(len(original))) + [5, 3]] values = original._values[list(range(len(original))) + [5, 3]] s = Series(values, index=idx, name='a') expected = Series([False] * len(original) + [True, True], index=idx, name='a') tm.assert_series_equal(s.duplicated(), expected) tm.assert_series_equal(s.drop_duplicates(), original) base = [False] * len(idx) base[3] = True base[5] = True expected = Series(base, index=idx, name='a') tm.assert_series_equal(s.duplicated(keep='last'), expected) tm.assert_series_equal(s.drop_duplicates(keep='last'), s[~np.array(base)]) # deprecate take_last with tm.assert_produces_warning(FutureWarning): tm.assert_series_equal( s.duplicated(take_last=True), expected) with tm.assert_produces_warning(FutureWarning): tm.assert_series_equal(s.drop_duplicates(take_last=True), s[~np.array(base)]) base = [False] * len(original) + [True, True] base[3] = True base[5] = True expected = Series(base, index=idx, name='a') tm.assert_series_equal(s.duplicated(keep=False), expected) tm.assert_series_equal(s.drop_duplicates(keep=False), s[~np.array(base)]) s.drop_duplicates(inplace=True) tm.assert_series_equal(s, original) def test_drop_duplicates_series_vs_dataframe(self): # GH 14192 df = pd.DataFrame({'a': [1, 1, 1, 'one', 'one'], 'b': [2, 2, np.nan, np.nan, np.nan], 'c': [3, 3, np.nan, np.nan, 'three'], 'd': [1, 2, 3, 4, 4], 'e': [datetime(2015, 1, 1), datetime(2015, 1, 1), datetime(2015, 2, 1), pd.NaT, pd.NaT] }) for column in df.columns: for keep in ['first', 'last', False]: dropped_frame = df[[column]].drop_duplicates(keep=keep) dropped_series = df[column].drop_duplicates(keep=keep) tm.assert_frame_equal(dropped_frame, dropped_series.to_frame()) def test_fillna(self): # # GH 11343 # though Index.fillna and Series.fillna has separate impl, # test here to confirm these works as the same for orig in self.objs: o = orig.copy() values = o.values # values will not be changed result = o.fillna(o.astype(object).values[0]) if isinstance(o, Index): self.assert_index_equal(o, result) else: self.assert_series_equal(o, result) # check shallow_copied self.assertFalse(o is result) for null_obj in [np.nan, None]: for orig in self.objs: o = orig.copy() klass = type(o) if not self._allow_na_ops(o): continue if needs_i8_conversion(o): values = o.astype(object).values fill_value = values[0] values[0:2] = pd.NaT else: values = o.values.copy() fill_value = o.values[0] values[0:2] = null_obj expected = [fill_value] * 2 + list(values[2:]) expected = klass(expected) o = klass(values) # check values has the same dtype as the original self.assertEqual(o.dtype, orig.dtype) result = o.fillna(fill_value) if isinstance(o, Index): self.assert_index_equal(result, expected) else: self.assert_series_equal(result, expected) # check shallow_copied self.assertFalse(o is result) def test_memory_usage(self): for o in self.objs: res = o.memory_usage() res_deep = o.memory_usage(deep=True) if (is_object_dtype(o) or (isinstance(o, Series) and is_object_dtype(o.index))): # if there are objects, only deep will pick them up self.assertTrue(res_deep > res) else: self.assertEqual(res, res_deep) if isinstance(o, Series): self.assertEqual( (o.memory_usage(index=False) + o.index.memory_usage()), o.memory_usage(index=True) ) # sys.getsizeof will call the .memory_usage with # deep=True, and add on some GC overhead diff = res_deep - sys.getsizeof(o) self.assertTrue(abs(diff) < 100) def test_searchsorted(self): # See gh-12238 for o in self.objs: index = np.searchsorted(o, max(o)) self.assertTrue(0 <= index <= len(o)) index = np.searchsorted(o, max(o), sorter=range(len(o))) self.assertTrue(0 <= index <= len(o)) def test_validate_bool_args(self): invalid_values = [1, "True", [1, 2, 3], 5.0] for value in invalid_values: with self.assertRaises(ValueError): self.int_series.drop_duplicates(inplace=value) class TestTranspose(Ops): errmsg = "the 'axes' parameter is not supported" def test_transpose(self): for obj in self.objs: if isinstance(obj, Index): tm.assert_index_equal(obj.transpose(), obj) else: tm.assert_series_equal(obj.transpose(), obj) def test_transpose_non_default_axes(self): for obj in self.objs: tm.assertRaisesRegexp(ValueError, self.errmsg, obj.transpose, 1) tm.assertRaisesRegexp(ValueError, self.errmsg, obj.transpose, axes=1) def test_numpy_transpose(self): for obj in self.objs: if isinstance(obj, Index): tm.assert_index_equal(np.transpose(obj), obj) else: tm.assert_series_equal(np.transpose(obj), obj) tm.assertRaisesRegexp(ValueError, self.errmsg, np.transpose, obj, axes=1) class TestNoNewAttributesMixin(tm.TestCase): def test_mixin(self): class T(NoNewAttributesMixin): pass t = T() self.assertFalse(hasattr(t, "__frozen")) t.a = "test" self.assertEqual(t.a, "test") t._freeze() # self.assertTrue("__frozen" not in dir(t)) self.assertIs(getattr(t, "__frozen"), True) def f(): t.b = "test" self.assertRaises(AttributeError, f) self.assertFalse(hasattr(t, "b")) if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], # '--with-coverage', '--cover-package=pandas.core'], exit=False)
pass
backend.py
## @package onnx # Module caffe2.python.onnx.backend """Backend for running ONNX on Caffe2 To run this, you will need to have Caffe2 installed as well. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import collections from subprocess import Popen, PIPE import sys import zipfile import itertools # When onnx is built against a version of protobuf that is older than # that which is vendored with caffe2, onnx will crash if caffe2's # vendored protobuf is loaded first. We can work around this by # importing onnx first, which will cause it to go out and pick up the # system protobuf. import onnx.backend import caffe2 from caffe2.python import core, workspace, rnn_cell, gru_cell from caffe2.python.compatibility import container_abcs from caffe2.python.model_helper import ModelHelper from caffe2.proto import caffe2_pb2 import caffe2.python.utils import numpy as np import onnx from onnx import checker, GraphProto, TensorProto, AttributeProto, ModelProto import onnx.numpy_helper import onnx.defs import onnx.optimizer import onnx.shape_inference import onnx.utils from onnx.backend.base import Backend, Device, DeviceType, namedtupledict from caffe2.python.onnx.workspace import Workspace from caffe2.python.onnx.backend_rep import Caffe2Rep from caffe2.python.onnx.backend_cpp_rep import Caffe2CppRep import caffe2.python._import_c_extension as C import warnings def force_unicode(s): try: return s.decode('utf-8') except AttributeError: return s def get_device_option(device): m = {DeviceType.CPU: caffe2_pb2.CPU, DeviceType.CUDA: workspace.GpuDeviceType} return core.DeviceOption(m[device.type], device.device_id) class OnnxAttributes(dict): """ This is a more convenient way to work with ONNX/Caffe2 attributes that is not the protobuf representation. """ @staticmethod def from_onnx(args): d = OnnxAttributes() for arg in args: d[arg.name] = convertAttributeProto(arg) return d def caffe2(self, kmap=lambda k: k): for k, v in self.items(): if kmap(k) != '': yield caffe2.python.utils.MakeArgument(kmap(k), v) # TODO: Move this into ONNX main library def convertAttributeProto(onnx_arg): """ Convert an ONNX AttributeProto into an appropriate Python object for the type. NB: Tensor attribute gets returned as the straight proto. """ if onnx_arg.HasField('f'): return onnx_arg.f elif onnx_arg.HasField('i'): return onnx_arg.i elif onnx_arg.HasField('s'): return onnx_arg.s elif onnx_arg.HasField('t'): return onnx_arg.t # this is a proto! elif onnx_arg.HasField('g'): return Caffe2Backend._graph_to_net(onnx_arg.g, Caffe2Backend._known_opset_version) elif len(onnx_arg.floats): return list(onnx_arg.floats) elif len(onnx_arg.ints): return list(onnx_arg.ints) elif len(onnx_arg.strings): return list(onnx_arg.strings) elif len(onnx_arg.graphs): retval = [] # TODO: this doesn't work with RNN ops for g in onnx_arg.graphs: retval.append(Caffe2Backend._graph_to_net(g, Caffe2Backend._known_opset_version)) return retval else: raise ValueError("Unsupported ONNX attribute: {}".format(onnx_arg)) # TODO: Move this into ONNX main library class OnnxNode(object): """ Reimplementation of NodeProto from ONNX, but in a form more convenient to work with from Python. We may temporarily edit these nodes to get them into Caffe2 form, before actually translating into the Caffe2 protobuf, since this is easier than decomposing everything, and putting it back together when we're ready. """ def __init__(self, node): self.name = str(node.name) self.op_type = str(node.op_type) self.attrs = OnnxAttributes.from_onnx(node.attribute) self.inputs = list(node.input) self.outputs = list(node.output) Caffe2Ops = collections.namedtuple('Caffe2Ops', ['ops', 'init_ops', 'interface_blobs']) class Caffe2Backend(Backend): # The greatest version of the ONNX operator set which we are aware of. # Models whose version is larger than this will cause us to emit a warning # that we are attempting to translate on a "best effort" basis. # # If you increase this, make SURE you cross-reference all BC-breaking # changes from one version to the next, and any that you did not # implement, mark as broken in _broken_operators _known_opset_version = 9 # This dictionary will record operators which are KNOWN to be # broken, so we give a good error message rather than do something # bogus and then fail. _broken_operators = { # 'BrokenOp': version_it_was_broken_in } # Operators that are different between Caffe2 and # ONNX but only in their name. # In most cases, this should be empty - as the effort of ONNX is # to unify the operator definitions. _renamed_operators = { 'GlobalMaxPool': 'MaxPool', 'GlobalAveragePool': 'AveragePool', 'Pad': 'PadImage', 'Neg': 'Negative', 'BatchNormalization': 'SpatialBN', 'InstanceNormalization': 'InstanceNorm', 'MatMul': 'BatchMatMul', 'Upsample': 'ResizeNearest', 'Identity': 'Copy', 'InstanceNormalization': 'InstanceNorm', 'Equal': 'EQ', 'Less': 'LT', 'Greater': 'GT', 'Unsqueeze': 'ExpandDims', 'Loop': 'ONNXWhile', 'Tile': 'NumpyTile', 'RandomNormal': 'GaussianFill', 'RandomUniform': 'UniformFill', } _global_renamed_attrs = {'kernel_shape': 'kernels'} _per_op_renamed_attrs = { 'Squeeze': {'axes': 'dims'}, 'Unsqueeze': {'axes': 'dims'}, 'Transpose': {'perm': 'axes'}, 'Upsample': {'mode': '', 'scales': ''}, 'ConvTranspose': {'output_padding': 'adjs'}, 'Selu': {'gamma': 'scale'}, 'If': {'then_branch': 'then_net', 'else_branch': 'else_net'}, 'RandomUniform': {'low': 'min', 'high': 'max'} } # operators whose behavior is different beyond renaming # the value is an attribute of this class that is a # function from ToffeIR node_def to caffe2 op_def _special_operators = { 'LSTM': '_create_rnn_variant', 'GRU': '_create_rnn_variant', 'RNN': '_create_rnn_variant', 'Loop': '_create_loop', 'If': '_create_if', 'Upsample': '_create_upsample', 'RandomNormal': '_create_gaussian_fill' } # Dummy name generator _dummy_name = C.DummyName() @classmethod def dummy_name(cls): return cls._dummy_name.new_dummy_name() # NB: By default, you will use the LATEST definition of the operator, # so this interface MAY make BC-breaking changes. Specify an # opset_version if you don't want this to version. @classmethod def run_node(cls, node, inputs, device='CPU', opset_version=_known_opset_version, outputs_info=None): super(Caffe2Backend, cls).run_node(node, inputs, device=device, outputs_info=outputs_info, opset_version=opset_version) value_infos = [] device_option = get_device_option(Device(device)) ws = Workspace() with core.DeviceScope(device_option): # temporary! if isinstance(inputs, dict): for key, value in inputs.items(): ws.FeedBlob(key, value) value_infos.append(onnx.helper.make_tensor_value_info( name=key, elem_type=onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[value.dtype], shape=value.shape).SerializeToString()) else: assert len(node.input) == len(inputs), "{}: expected {} but got {}".format( node.op_type, len(node.input), len(inputs)) for key, value in zip(node.input, inputs): ws.FeedBlob(key, value) value_infos.append(onnx.helper.make_tensor_value_info( name=key, elem_type=onnx.mapping.NP_TYPE_TO_TENSOR_TYPE[value.dtype], shape=value.shape).SerializeToString()) ops = [] cbackend = C.Caffe2Backend(cls._dummy_name) ops_str = cbackend.convert_node(node.SerializeToString(), value_infos, opset_version) for s in ops_str[0] + ops_str[1]: op = caffe2_pb2.OperatorDef() op.ParseFromString(s) op.device_option.CopyFrom(device_option) ops.append(op) ws.RunOperatorsOnce(ops) output_values = [ws.FetchBlob(name) for name in node.output] return namedtupledict('Outputs', node.output)(*output_values) @classmethod def _create_tensor_filling_op(cls, onnx_tensor, name=None): """ Given an Onnx TensorProto, translate it into a Caffe2 operator which produces the given tensor filling op. """ assert name or onnx_tensor.name name = name or onnx_tensor.name c2_op = caffe2_pb2.OperatorDef() c2_values = c2_op.arg.add() c2_values.name = "values" def tensor2list(onnx_tensor): # Use the onnx.numpy_helper because the data may be raw return onnx.numpy_helper.to_array(onnx_tensor).flatten().tolist() if onnx_tensor.data_type in [TensorProto.FLOAT]: c2_op.type = 'GivenTensorFill' c2_values.floats.extend(tensor2list(onnx_tensor)) elif onnx_tensor.data_type in [TensorProto.DOUBLE]: c2_op.type = 'GivenTensorDoubleFill' c2_values.floats.extend(tensor2list(onnx_tensor)) elif onnx_tensor.data_type in [TensorProto.INT64, TensorProto.UINT32]: c2_op.type = 'GivenTensorInt64Fill' c2_values.ints.extend(tensor2list(onnx_tensor)) elif onnx_tensor.data_type in [TensorProto.UINT8, TensorProto.INT8, TensorProto.UINT16, TensorProto.INT16, TensorProto.INT32]: c2_op.type = 'GivenTensorIntFill' c2_values.ints.extend(tensor2list(onnx_tensor)) elif onnx_tensor.data_type == TensorProto.BOOL: c2_op.type = 'GivenTensorBoolFill' c2_values.ints.extend(tensor2list(onnx_tensor)) elif onnx_tensor.data_type == TensorProto.STRING: c2_op.type = 'GivenTensorStringFill' c2_values.strings.extend(onnx_tensor.string_data) else: raise RuntimeError( "unrecognized tensor type {}".format(onnx_tensor.data_type)) c2_shape = c2_op.arg.add() c2_shape.name = "shape" c2_shape.ints.extend(onnx_tensor.dims) c2_op.output.append(name) return c2_op @classmethod def _rnn_reform_weights(cls, reforms, name, hidden_size, init_net, gates, reorder_indices): for name_from, name_to, do_concat, extra_dims in reforms: gate_blobs = ['%s/%s_%s' % (name, prefix, name_to) for prefix in gates] for i, x in enumerate(gate_blobs): dim0 = i * hidden_size, (i+1) * hidden_size starts, ends = zip(dim0, *extra_dims) init_net.Slice(name_from, x, starts=starts, ends=ends) if do_concat: reordered_gate_blobs = [gate_blobs[i] for i in reorder_indices] init_net.Concat(reordered_gate_blobs, ['%s/%s' % (name, name_to), cls.dummy_name()], axis=0) @classmethod def _make_rnn_direction(cls, input_blob, B, W, R, initial_states_and_names, sequence_lens, pred_mh, init_net, input_size, hidden_size, num_gates, direction_offset, Bi, Br, W_, R_, reform, make_cell, keep_outputs): name = cls.dummy_name() # input and recurrence biases are squashed together in onnx # but not in caffe2 gates_hidden_size = num_gates * hidden_size bias_offset = 2 * direction_offset * gates_hidden_size weight_offset = direction_offset * gates_hidden_size Bi = init_net.Slice(B, name + Bi, starts=[bias_offset + 0 * gates_hidden_size], ends =[bias_offset + 1 * gates_hidden_size]) Br = init_net.Slice(B, name + Br, starts=[bias_offset + 1 * gates_hidden_size], ends =[bias_offset + 2 * gates_hidden_size]) W_ = init_net.Slice(W, name + W_, starts=[weight_offset + 0 * gates_hidden_size, 0], ends =[weight_offset + 1 * gates_hidden_size,-1]) R_ = init_net.Slice(R, name + R_, starts=[weight_offset + 0 * gates_hidden_size, 0], ends =[weight_offset + 1 * gates_hidden_size,-1]) initial_states_sliced = [] for initial_state, name_suffix in initial_states_and_names: initial_states_sliced.append( pred_mh.net.Slice(initial_state, name + name_suffix, starts=[direction_offset + 0, 0, 0], ends =[direction_offset + 1,-1,-1])) if direction_offset == 1: if sequence_lens is not None: seq_lens_for_reverse = sequence_lens else: input_shape = pred_mh.net.Shape(input_blob, name + '/input_shape') batch_size = pred_mh.net.Slice(input_shape, name + '/batch_size_slice', starts=[1], ends=[2]) seq_len = pred_mh.net.Slice(input_shape, name + '/seq_len_slice', starts=[0], ends=[1]) dummy_sequence_lens = pred_mh.net.Tile([seq_len, batch_size], name + '/dummy_sequence_lens', axis=0) pred_mh.net.Reshape(dummy_sequence_lens, [dummy_sequence_lens, cls.dummy_name()], shape=[-1]) seq_lens_for_reverse = pred_mh.net.Cast(dummy_sequence_lens, name + '/seq_lens_for_reverse', to=core.DataType.INT32) reform(Bi, Br, W_, R_, name, hidden_size, init_net) if direction_offset == 1: input = pred_mh.net.ReversePackedSegs( [input_blob, seq_lens_for_reverse], name + "/input-reversed") else: input = input_blob outputs = keep_outputs(list(make_cell( pred_mh, input, sequence_lens, initial_states_sliced, input_size, hidden_size, name, drop_states=False, forward_only=True, ))) if direction_offset == 1: outputs[0] = pred_mh.net.ReversePackedSegs( [outputs[0], seq_lens_for_reverse], name + "/output-reversed") return outputs @classmethod def _create_rnn_variant(cls, init_model, pred_model, n, opset_version):
@classmethod def _create_control_op(cls, init_model, pred_model, n, opset_version): control_inputs = [] if '__control_inputs' in n.attrs: control_inputs.extend(n.attrs['__control_inputs']) node = cls._common_onnx_node_to_caffe2_op(init_model, pred_model, n, opset_version) node.control_input.extend(control_inputs) return Caffe2Ops([node], [], []) @classmethod def _remove_ssa(cls, net, remap_dict): for op in net.op: for i, name in enumerate(op.output): if name in remap_dict: op.output[i] = remap_dict[name] for i, out in enumerate(net.external_output): if out in remap_dict: net.external_output[i] = remap_dict[out] @classmethod def _create_if(cls, init_model, pred_model, n, opset_version): ops = cls._create_control_op(init_model, pred_model, n, opset_version) assert ops[0][0].type == 'If' if_op = ops[0][0] then_net = else_net = None control_inputs = [] for arg in if_op.arg: if arg.name == 'then_net': then_net = arg.n if arg.name == 'else_net': else_net = arg.n if arg.name == '__control_inputs': control_inputs = arg.strings assert then_net and else_net then_net_outs = then_net.external_output else_net_outs = else_net.external_output op_outputs = if_op.output assert len(then_net_outs) == len(else_net_outs) assert len(else_net_outs) == len(op_outputs) for arg in if_op.arg: if arg.name == 'then_net': arg.n.external_input.extend(control_inputs) if arg.name == 'else_net': arg.n.external_input.extend(control_inputs) return ops @classmethod def _create_loop(cls, init_model, pred_model, n, opset_version): ops = cls._create_control_op(init_model, pred_model, n, opset_version) assert ops[0][0].type == 'ONNXWhile' while_op = ops[0][0] while_op.arg.extend([caffe2.python.utils.MakeArgument('has_trip_count', True)]) while_op.arg.extend([caffe2.python.utils.MakeArgument('has_cond', True)]) while_op.arg.extend([caffe2.python.utils.MakeArgument('disable_scopes', True)]) control_inputs = [] for arg in while_op.arg: if arg.name == '__control_inputs': control_inputs = arg.strings num_loop_carried_deps = 0 for arg in while_op.arg: if arg.name == 'body': num_loop_carried_deps = len(arg.n.external_input) - 2 arg.n.external_input.extend(control_inputs) while_op.arg.extend([ caffe2.python.utils.MakeArgument('num_loop_carried_deps', num_loop_carried_deps) ]) return ops @classmethod def _substitute_raw_value(cls, tp, raw_values_dict): if tp.HasField('raw_data') and tp.raw_data == bytes(b'__EXTERNAL'): if tp.name not in raw_values_dict: raise RuntimeError('TensorProto for value {} referenced raw data but it was not found!'.format(tp.name)) else: tp.raw_data = raw_values_dict[tp.name] @classmethod def _visit_and_substitute_raw_values(cls, nodes, raw_values_dict): for node in nodes: for attr in node.attribute: if attr.HasField('t'): cls._substitute_raw_value(attr.t, raw_values_dict) for t in attr.tensors: cls._substitute_raw_value(t, raw_values_dict) if attr.HasField('g'): cls._visit_and_substitute_raw_values(attr.g.node, raw_values_dict) for g in attr.graphs: cls._visit_and_substitute_raw_values(g.node, raw_values_dict) @classmethod def _external_value_resolution_pass(cls, model, raw_values_dict): for init in model.graph.initializer: cls._substitute_raw_value(init, raw_values_dict) cls._visit_and_substitute_raw_values(model.graph.node, raw_values_dict) @classmethod def _direct_initialize_parameters(cls, initializer, ws, device_option): for tp in initializer: ws.FeedBlob(tp.name, onnx.numpy_helper.to_array(tp), device_option) @classmethod def _direct_initialize_inputs(cls, inputs, initialized, ws, device_option): for value_info in inputs: if value_info.name in initialized: continue shape = list(d.dim_value for d in value_info.type.tensor_type.shape.dim) ws.FeedBlob( value_info.name, np.ones(shape, dtype=onnx.mapping.TENSOR_TYPE_TO_NP_TYPE[value_info.type.tensor_type.elem_type]), device_option) @staticmethod def optimize_onnx(input, init=False, predict=False): passes = ['fuse_consecutive_transposes', 'eliminate_nop_transpose', 'fuse_transpose_into_gemm', 'lift_lexical_references'] if init: passes.append('split_init') if predict: passes.append('split_predict') out = onnx.optimizer.optimize(input, passes) return out @classmethod def prepare_zip_archive(cls, file, device='CPU', **kwargs): with zipfile.ZipFile(file, mode='r') as z: with z.open('__MODEL_PROTO', 'r') as f: model = onnx.load(f); blob_names = set(z.namelist()) - set('__MODEL_PROTO') # TODO: make this more efficient raw_values_dict = {} for name in blob_names: with z.open(name, 'r') as blob_file: raw_values_dict[name] = blob_file.read() return cls.prepare(model, device, raw_values_dict=raw_values_dict, **kwargs) @classmethod def prepare(cls, model, device='CPU', raw_values_dict=None, **kwargs): ''' For Onnx Caffe2Backend, we require that init_graph don't initialize the actual input of the predict_graph, for example, if "img" is the input blob for the predict_net, we require that in init_graph and in initializer of the predict_graph, "img" is not initalized. We don't have a check for this, since there is no way we can know which blob is the input of the predict_graph. ''' if not kwargs.pop('no_check_UNSAFE', False): super(Caffe2Backend, cls).prepare(model, device, **kwargs) opset_version = None for imp in model.opset_import: if not imp.HasField("domain") or imp.domain == "": opset_version = imp.version if imp.version > cls._known_opset_version: warnings.warn("This version of onnx-caffe2 targets ONNX operator set version {}, but the model we are trying to import uses version {}. We will try to import it anyway, but if the model uses operators which had BC-breaking changes in the intervening versions, import will fail.".format(cls._known_opset_version, imp.version)) else: warnings.warn("Unrecognized operator set {}".format(imp.domain)) if opset_version is None: if model.ir_version >= 0x00000003: raise RuntimeError("Model with IR version >= 3 did not specify ONNX operator set version (onnx-caffe2 requires it)") else: opset_version = 1 model = onnx.shape_inference.infer_shapes(model) ws = Workspace() device_option = get_device_option(Device(device)) init_net, predict_net = cls._onnx_model_to_caffe2_net(model, device, opset_version, False) if raw_values_dict: cls._external_value_resolution_pass(model, raw_values_dict) # Directly load initializer data into blobs in workspace cls._direct_initialize_parameters( model.graph.initializer, ws, device_option, ) initialized = {init.name for init in model.graph.initializer} cls._direct_initialize_inputs( model.graph.input, initialized, ws, device_option, ) uninitialized = [value_info.name for value_info in model.graph.input if value_info.name not in initialized] retval = Caffe2Rep(init_net, predict_net, ws, uninitialized) return retval @classmethod # TODO: This method needs a refactor for clarity def _onnx_node_to_caffe2_op(cls, init_model, pred_model, node_def, opset_version): cbackend = C.Caffe2Backend(cls._dummy_name) if cbackend.support_onnx_import(node_def.op_type): # extract value infos from pred model (value infos of # node's inputs that are in init model should be all # available in pred model) value_infos = [] for name in node_def.input: if pred_model is not None: for vi in itertools.chain(pred_model.graph.input, pred_model.graph.output, pred_model.graph.value_info): if vi.name == name: value_infos.append(vi.SerializeToString()) op_strs = cbackend.convert_node(node_def.SerializeToString(), value_infos, opset_version) init_ops = [] for s in op_strs[0]: op = caffe2_pb2.OperatorDef() op.ParseFromString(s) init_ops.append(op) ops = [] for s in op_strs[1]: op = caffe2_pb2.OperatorDef() op.ParseFromString(s) ops.append(op) return Caffe2Ops(ops, init_ops, []) if node_def.op_type in cls._special_operators: translator = getattr(cls, cls._special_operators[node_def.op_type]) else: translator = cls._common_onnx_node_to_caffe2_op ops = translator(init_model, pred_model, OnnxNode(node_def), opset_version) if isinstance(ops, Caffe2Ops): return ops if not isinstance(ops, container_abcs.Iterable): ops = [ops] return Caffe2Ops(ops, [], []) _broadcast_operators = { 'Add', 'Sub', } @classmethod def _common_onnx_node_to_caffe2_op(cls, init_model, pred_model, onnx_node, opset_version): """ This translator performs the basic translation of ONNX nodes into Caffe2 operators. Besides doing a straightforward marshalling from one format to another, it also does these extra things: - Renames operators based on '_renamed_operators' - Renames attributes based on '_global_renamed_attrs' and '_per_op_renamed_attrs' If you're writing a custom translator, consider calling this first, and then fixing things up further. """ c2_op = caffe2_pb2.OperatorDef() c2_op.input.extend(onnx_node.inputs) c2_op.output.extend(onnx_node.outputs) c2_op.name = onnx_node.name onnx_op_type = onnx_node.op_type broken_version = cls._broken_operators.get(onnx_op_type, float('Inf')) if broken_version <= opset_version: raise ValueError( "Don't know how to translate op {} in ONNX operator set v{} (I only support prior to v{})".format(onnx_op_type, opset_version, broken_version)) c2_op.type = cls._renamed_operators.get(onnx_op_type, onnx_op_type) if not core.IsOperator(c2_op.type): raise ValueError( "Don't know how to translate op {}".format(onnx_op_type)) def kmap(k): if (onnx_op_type in cls._per_op_renamed_attrs and k in cls._per_op_renamed_attrs[onnx_op_type]): return cls._per_op_renamed_attrs[onnx_op_type][k] if k in cls._global_renamed_attrs: return cls._global_renamed_attrs[k] return k c2_op.arg.extend(onnx_node.attrs.caffe2(kmap=kmap)) if opset_version < 7: # onnx opset 7 and newest caffe2 have adopted full onnx broadcast semantics # so we don't need this hack anymore if c2_op.type in cls._broadcast_operators: already_broadcast = False for arg in c2_op.arg: if arg.name == 'broadcast': already_broadcast = True if not already_broadcast: c2_op.arg.extend([caffe2.python.utils.MakeArgument('broadcast', 1)]) return c2_op @staticmethod def _all_names_in_graph(graph): if graph is None: return set() names = set() names.update(value_info.name for value_info in graph.input) names.update(value_info.name for value_info in graph.output) for node in graph.node: names.update(node.input) names.update(node.output) return names @classmethod def _graph_to_net(cls, onnx_graph, opset_version): net = caffe2_pb2.NetDef() for node in onnx_graph.node: try: c2ops = cls._onnx_node_to_caffe2_op( None, None, node, opset_version) except Exception as e: print('ONNX FATAL:', e) continue net.op.extend(c2ops.init_ops) net.op.extend(c2ops.ops) net.external_input.extend(c2ops.interface_blobs) net.external_output.extend( value_info.name for value_info in onnx_graph.output) net.external_input.extend( value_info.name for value_info in onnx_graph.input) return net @classmethod def _onnx_model_to_caffe2_net(cls, onnx_model, device, opset_version, include_initializers): device_option = get_device_option(Device(device)) onnx_model = onnx.utils.polish_model(onnx_model) init_model = cls.optimize_onnx(onnx_model, init=True) pred_model = cls.optimize_onnx(onnx_model, predict=True) init_net = caffe2_pb2.NetDef() pred_net = caffe2_pb2.NetDef() init_net.name = onnx_model.graph.name + '_init' pred_net.name = onnx_model.graph.name + '_predict' if include_initializers: init_net.op.extend(cls._create_tensor_filling_op(tp) for tp in onnx_model.graph.initializer) cls._dummy_name.reset(cls._all_names_in_graph(init_model.graph) | cls._all_names_in_graph(pred_model.graph)) errors = [] for net, model in ( (init_net, init_model), (pred_net, pred_model) ): net.device_option.CopyFrom(device_option) for node in model.graph.node: try: c2ops = cls._onnx_node_to_caffe2_op( init_model, pred_model, node, opset_version) except Exception as e: msg = 'Error while processing node: {}. Exception: {}'.format(node, e) errors.append(msg) print('ONNX FATAL:', msg, file=sys.stderr) continue init_net.op.extend(c2ops.init_ops) net.op.extend(c2ops.ops) net.external_input.extend(c2ops.interface_blobs) net.external_output.extend( value_info.name for value_info in model.graph.output) net.external_input.extend( value_info.name for value_info in model.graph.input) if len(errors) > 0: raise RuntimeError( "ONNX conversion failed, encountered {} errors:\n\n{}".format( len(errors), "\n\n".join(errors))) return init_net, pred_net # wrapper for backwards compatability @classmethod def onnx_graph_to_caffe2_net(cls, model, device="CPU", opset_version=_known_opset_version): return cls._onnx_model_to_caffe2_net(model, device=device, opset_version=opset_version, include_initializers=True) @classmethod def supports_device(cls, device_str): device = Device(device_str) if device.type == DeviceType.CPU: return True elif core.IsGPUDeviceType(device.type): return workspace.has_gpu_support return False @classmethod def is_compatible(cls, model, device='CPU', **kwargs): if hasattr(super(Caffe2Backend, cls), 'is_compatible') \ and callable(super(Caffe2Backend, cls).is_compatible): if not super(Caffe2Backend, cls).is_compatible(model, device, **kwargs): return False # TODO: should have an unspported list of operators, be optimistic for now return True prepare = Caffe2Backend.prepare prepare_zip_archive = Caffe2Backend.prepare_zip_archive run_node = Caffe2Backend.run_node run_model = Caffe2Backend.run_model supports_device = Caffe2Backend.supports_device # noqa is_compatible = Caffe2Backend.is_compatible
assert init_model is not None, "cannot convert RNNs without access to the full model" assert pred_model is not None, "cannot convert RNNs without access to the full model" attrs = dict(n.attrs) # make a copy, which is safe to mutate hidden_size = attrs.pop('hidden_size') direction = force_unicode(attrs.pop('direction', 'forward')) if n.op_type == 'RNN': activation = force_unicode(attrs.pop('activations', ('tanh',))[0].lower()) elif n.op_type == 'GRU': linear_before_reset = attrs.pop('linear_before_reset', 0) assert not attrs, "unsupported RNN attributes: " + str(attrs.keys()) assert direction in ['forward', 'bidirectional'], "unsupported backwards RNN/GRU/LSTM" if n.op_type in ['RNN', 'GRU']: input_blob, W, R, B, sequence_lens, initial_h = n.inputs elif n.op_type == 'LSTM': input_blob, W, R, B, sequence_lens, initial_h, initial_c = n.inputs if sequence_lens == "": sequence_lens = None for x in itertools.chain(init_model.graph.input, init_model.graph.value_info, pred_model.graph.input, pred_model.graph.value_info): if x.name == W: input_size = x.type.tensor_type.shape.dim[2].dim_value break else: raise RuntimeError("best-effort shape inference for RNN/GRU/LSTM failed") pred_mh = ModelHelper() init_net = core.Net("init-net") init_net.Reshape(W, [W, cls.dummy_name()], shape=[1,-1,0]) init_net.Squeeze(W, W, dims=[0]) init_net.Reshape(R, [R, cls.dummy_name()], shape=[1,-1,0]) init_net.Squeeze(R, R, dims=[0]) init_net.Reshape(B, [B, cls.dummy_name()], shape=[1,-1]) init_net.Squeeze(B, B, dims=[0]) if n.op_type == 'RNN': def reform(*args): pass def make_cell(*args, **kwargs): return rnn_cell.BasicRNN(*args, activation=activation, **kwargs) def make_rnn(direction_offset): return cls._make_rnn_direction( input_blob, B, W, R, [(initial_h, '/initial_h')], sequence_lens, pred_mh, init_net, input_size, hidden_size, 1, direction_offset, "/i2h_b", "/gates_t_b", "/i2h_w", "/gates_t_w", reform, make_cell, lambda x: x) elif n.op_type == 'GRU': def reform(Bi, Br, W_, R_, name, hidden_size, init_net): # caffe2 has a different order from onnx. We need to rearrange # z r h -> r z h reforms = ((W_, 'i2h_w', True, [(0,-1)]), (R_, 'gate_t_w', False, [(0,-1)]), (Bi, 'i2h_b', True, []), (Br, 'gate_t_b', False, [])) cls._rnn_reform_weights(reforms, name, hidden_size, init_net, ['update', 'reset', 'output'], [1, 0, 2]) def make_cell(*args, **kwargs): return gru_cell.GRU(*args, linear_before_reset=linear_before_reset, **kwargs) def make_rnn(direction_offset): return cls._make_rnn_direction( input_blob, B, W, R, [(initial_h, '/initial_h')], sequence_lens, pred_mh, init_net, input_size, hidden_size, 3, direction_offset, "_bias_i2h", "_bias_gates", "/i2h_w_pre", "/gates_t_w_pre", reform, make_cell, lambda x: x) elif n.op_type == 'LSTM': def reform(Bi, Br, W_, R_, name, hidden_size, init_net): # caffe2 has a different order from onnx. We need to rearrange # i o f c -> i f o c reforms = ((W_, 'i2h_w', True, [(0, -1)]), (R_, 'gates_t_w', True, [(0, -1)]), (Bi, 'i2h_b' , True, []), (Br, 'gates_t_b', True, [])) cls._rnn_reform_weights(reforms, name, hidden_size, init_net, ['input', 'output', 'forget', 'cell'], [0, 2, 1, 3]) def make_cell(*args, **kwargs): return rnn_cell.LSTM(*args, **kwargs) def make_rnn(direction_offset): return cls._make_rnn_direction( input_blob, B, W, R, [(initial_h, '/initial_h'), (initial_c, '/initial_c')], sequence_lens, pred_mh, init_net, input_size, hidden_size, 4, direction_offset, "/i2h_b", "/gates_t_b", "/i2h_w", "/gates_t_w", reform, make_cell, lambda x: [x[0], x[1], x[3]]) if direction == 'forward': outputs = make_rnn(0) # in the forward case, storage is shared between the # last outputs. We need to decouple them so that the # VariableLengthSequencePadding only mutates # n.outputs[0] for i in range(1, len(outputs)): pred_mh.net.Copy(outputs[i], n.outputs[i]) if sequence_lens is not None: pred_mh.net.VariableLengthSequencePadding( [outputs[0], sequence_lens], [outputs[0]]) pred_mh.net.ExpandDims([outputs[0]], [n.outputs[0]], dims=[1]) elif direction == 'bidirectional': outputs_f = make_rnn(0) outputs_b = make_rnn(1) concatted_output, _ = pred_mh.net.Concat( [outputs_f[0], outputs_b[0]], [cls.dummy_name(), cls.dummy_name()], axis=2) if sequence_lens is not None: pred_mh.net.VariableLengthSequencePadding( [concatted_output, sequence_lens], [concatted_output]) reshaped_output, _ = pred_mh.net.Reshape(concatted_output, [cls.dummy_name(), cls.dummy_name()], shape=[0,0,-1,2]) pred_mh.net.Transpose(reshaped_output, n.outputs[0], axes=[0,2,1,3]) for i in range(1, len(n.outputs)): pred_mh.net.Concat([outputs_f[i], outputs_b[i]], [n.outputs[i], cls.dummy_name()], axis=0) # We want to decide whether to put all of our weight-reshaping # operators in the init net or the predict net. We can put # them in the init net iff the inputs to those operators are # already available, either as graph initializers, or as the # output of other operators in the init net. The latter case # occurs, for example, when exporting from pytorch to onnx. # In most production use, we expect has_initializers to be # true. initializers = {i.name for i in init_model.graph.initializer} outputs = {output for node in init_model.graph.node for output in node.output} has_initializers = all(x in initializers or x in outputs for x in (W, R, B)) pred_ops = [] init_ops = [] (init_ops if has_initializers else pred_ops).extend(init_net.Proto().op) pred_ops.extend(pred_mh.Proto().op) return Caffe2Ops(pred_ops, init_ops, list(pred_mh.Proto().external_input))
win32popen.py
# -*-python-*- # # Copyright (C) 1999-2015 The ViewCVS Group. All Rights Reserved. # # By using this file, you agree to the terms and conditions set forth in # the LICENSE.html file which can be found at the top level of the ViewVC # distribution or at http://viewvc.org/license-1.html. # # For more information, visit http://viewvc.org/ # # ----------------------------------------------------------------------- # # Utilities for controlling processes and pipes on win32 # # ----------------------------------------------------------------------- import os, sys, traceback, string, thread try: import win32api except ImportError, e: raise ImportError, str(e) + """ Did you install the Python for Windows Extensions? http://sourceforge.net/projects/pywin32/ """ import win32process, win32pipe, win32con import win32event, win32file, winerror import pywintypes, msvcrt # Buffer size for spooling SPOOL_BYTES = 4096 # File object to write error messages SPOOL_ERROR = sys.stderr #SPOOL_ERROR = open("m:/temp/error.txt", "wt") def CommandLine(command, args): """Convert an executable path and a sequence of arguments into a command line that can be passed to CreateProcess""" cmd = "\"" + string.replace(command, "\"", "\"\"") + "\"" for arg in args: cmd = cmd + " \"" + string.replace(arg, "\"", "\"\"") + "\"" return cmd def CreateProcess(cmd, hStdInput, hStdOutput, hStdError): """Creates a new process which uses the specified handles for its standard input, output, and error. The handles must be inheritable. 0 can be passed as a special handle indicating that the process should inherit the current process's input, output, or error streams, and None can be passed to discard the child process's output or to prevent it from reading any input.""" # initialize new process's startup info si = win32process.STARTUPINFO() si.dwFlags = win32process.STARTF_USESTDHANDLES if hStdInput == 0: si.hStdInput = win32api.GetStdHandle(win32api.STD_INPUT_HANDLE) else: si.hStdInput = hStdInput if hStdOutput == 0: si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE) else: si.hStdOutput = hStdOutput if hStdError == 0: si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE) else: si.hStdError = hStdError # create the process phandle, pid, thandle, tid = win32process.CreateProcess \ ( None, # appName cmd, # commandLine None, # processAttributes None, # threadAttributes 1, # bInheritHandles win32con.NORMAL_PRIORITY_CLASS, # dwCreationFlags None, # newEnvironment None, # currentDirectory si # startupinfo ) if hStdInput and hasattr(hStdInput, 'Close'): hStdInput.Close() if hStdOutput and hasattr(hStdOutput, 'Close'): hStdOutput.Close() if hStdError and hasattr(hStdError, 'Close'): hStdError.Close() return phandle, pid, thandle, tid def CreatePipe(readInheritable, writeInheritable): """Create a new pipe specifying whether the read and write ends are inheritable and whether they should be created for blocking or nonblocking I/O.""" r, w = win32pipe.CreatePipe(None, SPOOL_BYTES) if readInheritable: r = MakeInheritedHandle(r) if writeInheritable: w = MakeInheritedHandle(w) return r, w def File2FileObject(pipe, mode): """Make a C stdio file object out of a win32 file handle""" if string.find(mode, 'r') >= 0: wmode = os.O_RDONLY elif string.find(mode, 'w') >= 0: wmode = os.O_WRONLY if string.find(mode, 'b') >= 0: wmode = wmode | os.O_BINARY if string.find(mode, 't') >= 0: wmode = wmode | os.O_TEXT return os.fdopen(msvcrt.open_osfhandle(pipe.Detach(),wmode),mode) def
(fileObject): """Get the win32 file handle from a C stdio file object""" return win32file._get_osfhandle(fileObject.fileno()) def DuplicateHandle(handle): """Duplicates a win32 handle.""" proc = win32api.GetCurrentProcess() return win32api.DuplicateHandle(proc,handle,proc,0,0,win32con.DUPLICATE_SAME_ACCESS) def MakePrivateHandle(handle, replace = 1): """Turn an inherited handle into a non inherited one. This avoids the handle duplication that occurs on CreateProcess calls which can create uncloseable pipes.""" ### Could change implementation to use SetHandleInformation()... flags = win32con.DUPLICATE_SAME_ACCESS proc = win32api.GetCurrentProcess() if replace: flags = flags | win32con.DUPLICATE_CLOSE_SOURCE newhandle = win32api.DuplicateHandle(proc,handle,proc,0,0,flags) if replace: handle.Detach() # handle was already deleted by the last call return newhandle def MakeInheritedHandle(handle, replace = 1): """Turn a private handle into an inherited one.""" ### Could change implementation to use SetHandleInformation()... flags = win32con.DUPLICATE_SAME_ACCESS proc = win32api.GetCurrentProcess() if replace: flags = flags | win32con.DUPLICATE_CLOSE_SOURCE newhandle = win32api.DuplicateHandle(proc,handle,proc,0,1,flags) if replace: handle.Detach() # handle was deleted by the last call return newhandle def MakeSpyPipe(readInheritable, writeInheritable, outFiles = None, doneEvent = None): """Return read and write handles to a pipe that asynchronously writes all of its input to the files in the outFiles sequence. doneEvent can be None, or a a win32 event handle that will be set when the write end of pipe is closed. """ if outFiles is None: return CreatePipe(readInheritable, writeInheritable) r, writeHandle = CreatePipe(0, writeInheritable) if readInheritable is None: readHandle, w = None, None else: readHandle, w = CreatePipe(readInheritable, 0) thread.start_new_thread(SpoolWorker, (r, w, outFiles, doneEvent)) return readHandle, writeHandle def SpoolWorker(srcHandle, destHandle, outFiles, doneEvent): """Thread entry point for implementation of MakeSpyPipe""" try: buffer = win32file.AllocateReadBuffer(SPOOL_BYTES) while 1: try: #print >> SPOOL_ERROR, "Calling ReadFile..."; SPOOL_ERROR.flush() hr, data = win32file.ReadFile(srcHandle, buffer) #print >> SPOOL_ERROR, "ReadFile returned '%s', '%s'" % (str(hr), str(data)); SPOOL_ERROR.flush() if hr != 0: raise "win32file.ReadFile returned %i, '%s'" % (hr, data) elif len(data) == 0: break except pywintypes.error, e: #print >> SPOOL_ERROR, "ReadFile threw '%s'" % str(e); SPOOL_ERROR.flush() if e.args[0] == winerror.ERROR_BROKEN_PIPE: break else: raise e #print >> SPOOL_ERROR, "Writing to %i file objects..." % len(outFiles); SPOOL_ERROR.flush() for f in outFiles: f.write(data) #print >> SPOOL_ERROR, "Done writing to file objects."; SPOOL_ERROR.flush() #print >> SPOOL_ERROR, "Writing to destination %s" % str(destHandle); SPOOL_ERROR.flush() if destHandle: #print >> SPOOL_ERROR, "Calling WriteFile..."; SPOOL_ERROR.flush() hr, bytes = win32file.WriteFile(destHandle, data) #print >> SPOOL_ERROR, "WriteFile() passed %i bytes and returned %i, %i" % (len(data), hr, bytes); SPOOL_ERROR.flush() if hr != 0 or bytes != len(data): raise "win32file.WriteFile() passed %i bytes and returned %i, %i" % (len(data), hr, bytes) srcHandle.Close() if doneEvent: win32event.SetEvent(doneEvent) if destHandle: destHandle.Close() except: info = sys.exc_info() SPOOL_ERROR.writelines(apply(traceback.format_exception, info), '') SPOOL_ERROR.flush() del info def NullFile(inheritable): """Create a null file handle.""" if inheritable: sa = pywintypes.SECURITY_ATTRIBUTES() sa.bInheritHandle = 1 else: sa = None return win32file.CreateFile("nul", win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, sa, win32file.OPEN_EXISTING, 0, None)
FileObject2File
users.go
package users import ( "net/http" "strconv" "github.com/cyrusroshan/API/utils" "github.com/cyrusroshan/SampleChatBackend/store" "github.com/go-martini/martini" ) func GetUsers(w http.ResponseWriter, r *http.Request, params martini.Params) (int, string) { return 200, string(utils.MustMarshal(store.Users)) } func NewUser(w http.ResponseWriter, r *http.Request, params martini.Params) (int, string) { userName := params["userName"] userId := store.NewUser(userName) return 200, string(utils.MustMarshal(userId)) } func DeleteUser(w http.ResponseWriter, r *http.Request, params martini.Params) (int, string) { useridString := params["userid"] userid, err := strconv.Atoi(useridString) utils.PanicIf(err)
delete(store.Users, userid) return 200, "" }
type.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _util = require('../util'); var util = _interopRequireWildcard(_util); var _required = require('./required'); var _required2 = _interopRequireDefault(_required); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } /* eslint max-len:0 */ var pattern = { email: /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/, url: new RegExp('^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$', 'i'), hex: /^#?([a-f0-9]{6}|[a-f0-9]{3})$/i }; var types = { integer: function integer(value) { return types.number(value) && parseInt(value, 10) === value; },
return types.number(value) && !types.integer(value); }, array: function array(value) { return Array.isArray(value); }, regexp: function regexp(value) { if (value instanceof RegExp) { return true; } try { return !!new RegExp(value); } catch (e) { return false; } }, date: function date(value) { return typeof value.getTime === 'function' && typeof value.getMonth === 'function' && typeof value.getYear === 'function'; }, number: function number(value) { if (isNaN(value)) { return false; } return typeof value === 'number'; }, object: function object(value) { return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && !types.array(value); }, method: function method(value) { return typeof value === 'function'; }, email: function email(value) { return typeof value === 'string' && !!value.match(pattern.email); }, url: function url(value) { return typeof value === 'string' && !!value.match(pattern.url); }, hex: function hex(value) { return typeof value === 'string' && !!value.match(pattern.hex); } }; /** * Rule for validating the type of a value. * * @param rule The validation rule. * @param value The value of the field on the source object. * @param source The source object being validated. * @param errors An array of errors that this rule may add * validation errors to. * @param options The validation options. * @param options.messages The validation messages. */ function type(rule, value, source, errors, options) { if (rule.required && value === undefined) { (0, _required2["default"])(rule, value, source, errors, options); return; } var custom = ['integer', 'float', 'array', 'regexp', 'object', 'method', 'email', 'number', 'date', 'url', 'hex']; var ruleType = rule.type; if (custom.indexOf(ruleType) > -1) { if (!types[ruleType](value)) { errors.push(util.format(options.messages.types[ruleType], rule.fullField, rule.type)); } // straight typeof check } else if (ruleType && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== rule.type) { errors.push(util.format(options.messages.types[ruleType], rule.fullField, rule.type)); } } exports["default"] = type; module.exports = exports['default'];
"float": function float(value) {
stats.go
// Package dfc provides distributed file-based cache with Amazon and Google Cloud backends. /* * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. * */ package dfc import ( "encoding/json" "fmt" "io/ioutil" "os" "os/exec" "sort" "strings" "sync" "syscall" "time" "github.com/golang/glog" ) const logsTotalSizeCheckTime = time.Hour * 3 //============================== // // types // //============================== type fscapacity struct { Used uint64 `json:"used"` // bytes Avail uint64 `json:"avail"` // ditto Usedpct uint32 `json:"usedpct"` // reduntant ok } // implemented by the stats runners type statslogger interface { log() (runlru bool) housekeep(bool) } // implemented by the ***CoreStats types type statsif interface { add(name string, val int64) addMany(nameval ...interface{}) } // TODO: use static map[string]int64 type proxyCoreStats struct { Numget int64 `json:"numget"` Numput int64 `json:"numput"` Numpost int64 `json:"numpost"` Numdelete int64 `json:"numdelete"` Numrename int64 `json:"numrename"` Numlist int64 `json:"numlist"` Getlatency int64 `json:"getlatency"` // microseconds Putlatency int64 `json:"putlatency"` // ---/--- Listlatency int64 `json:"listlatency"` // ---/--- Numerr int64 `json:"numerr"` // omitempty ngets int64 `json:"-"` nputs int64 `json:"-"` nlists int64 `json:"-"` logged bool `json:"-"` } type targetCoreStats struct { proxyCoreStats Numcoldget int64 `json:"numcoldget"` Bytesloaded int64 `json:"bytesloaded"` Bytesevicted int64 `json:"bytesevicted"` Filesevicted int64 `json:"filesevicted"` Numsentfiles int64 `json:"numsentfiles"` Numsentbytes int64 `json:"numsentbytes"` Numrecvfiles int64 `json:"numrecvfiles"` Numrecvbytes int64 `json:"numrecvbytes"` Numprefetch int64 `json:"numprefetch"` Bytesprefetched int64 `json:"bytesprefetched"` Numvchanged int64 `json:"numvchanged"` Bytesvchanged int64 `json:"bytesvchanged"` Numbadchecksum int64 `json:"numbadchecksum"` Bytesbadchecksum int64 `json:"bytesbadchecksum"` } type statsrunner struct { sync.Mutex namedrunner statslogger chsts chan struct{} } type proxystatsrunner struct { statsrunner `json:"-"` Core proxyCoreStats `json:"core"` } type deviometrics map[string]string type storstatsrunner struct { statsrunner `json:"-"` Core targetCoreStats `json:"core"` Capacity map[string]*fscapacity `json:"capacity"` // iostat CPUidle string `json:"cpuidle"` Disk map[string]deviometrics `json:"disk"` // omitempty timeUpdatedCapacity time.Time `json:"-"` timeCheckedLogSizes time.Time `json:"-"` fsmap map[syscall.Fsid]string `json:"-"` } type ClusterStats struct { Proxy *proxyCoreStats `json:"proxy"` Target map[string]*storstatsrunner `json:"target"` } type iostatrunner struct { sync.Mutex namedrunner chsts chan struct{} CPUidle string metricnames []string Disk map[string]deviometrics cmd *exec.Cmd } //============================================================== // // c-tor and methods // //============================================================== func newClusterStats() *ClusterStats
//================== // // common statsunner // //================== func (r *statsrunner) runcommon(logger statslogger) error { r.chsts = make(chan struct{}, 4) glog.Infof("Starting %s", r.name) ticker := time.NewTicker(ctx.config.StatsTime) for { select { case <-ticker.C: runlru := logger.log() logger.housekeep(runlru) case <-r.chsts: ticker.Stop() return nil } } } func (r *statsrunner) stop(err error) { glog.Infof("Stopping %s, err: %v", r.name, err) var v struct{} r.chsts <- v close(r.chsts) } // statslogger interface impl func (r *statsrunner) log() (runlru bool) { assert(false) return false } func (r *statsrunner) housekeep(bool) { } //================= // // proxystatsrunner // //================= func (r *proxystatsrunner) run() error { return r.runcommon(r) } // statslogger interface impl func (r *proxystatsrunner) log() (runlru bool) { r.Lock() if r.Core.logged { r.Unlock() return } if r.Core.ngets > 0 { r.Core.Getlatency /= r.Core.ngets } if r.Core.nputs > 0 { r.Core.Putlatency /= r.Core.nputs } if r.Core.nlists > 0 { r.Core.Listlatency /= r.Core.nlists } b, err := json.Marshal(r.Core) r.Core.Getlatency, r.Core.Putlatency, r.Core.Listlatency = 0, 0, 0 r.Core.ngets, r.Core.nputs, r.Core.nlists = 0, 0, 0 r.Unlock() if err == nil { glog.Infoln(string(b)) r.Core.logged = true } return } func (r *proxystatsrunner) add(name string, val int64) { r.Lock() r.addLocked(name, val) r.Unlock() } func (r *proxystatsrunner) addMany(nameval ...interface{}) { r.Lock() defer r.Unlock() i := 0 for i < len(nameval) { statsname, ok := nameval[i].(string) assert(ok, fmt.Sprintf("Invalid stats name: %v, %T", nameval[i], nameval[i])) i++ statsval, ok := nameval[i].(int64) assert(ok, fmt.Sprintf("Invalid stats type: %v, %T", nameval[i], nameval[i])) i++ r.addLocked(statsname, statsval) } } func (r *proxystatsrunner) addLocked(name string, val int64) { var v *int64 s := &r.Core switch name { case "numget": v = &s.Numget case "numput": v = &s.Numput case "numpost": v = &s.Numpost case "numdelete": v = &s.Numdelete case "numrename": v = &s.Numrename case "numlist": v = &s.Numlist case "getlatency": v = &s.Getlatency s.ngets++ case "putlatency": v = &s.Putlatency s.nputs++ case "listlatency": v = &s.Listlatency s.nlists++ case "numerr": v = &s.Numerr default: assert(false, "Invalid stats name "+name) } *v += val s.logged = false } //================ // // storstatsrunner // //================ func (r *storstatsrunner) run() error { return r.runcommon(r) } func (r *storstatsrunner) log() (runlru bool) { r.Lock() if r.Core.logged { r.Unlock() return } lines := make([]string, 0, 16) // core stats if r.Core.ngets > 0 { r.Core.Getlatency /= r.Core.ngets } if r.Core.nputs > 0 { r.Core.Putlatency /= r.Core.nputs } if r.Core.nlists > 0 { r.Core.Listlatency /= r.Core.nlists } b, err := json.Marshal(r.Core) r.Core.Getlatency, r.Core.Putlatency, r.Core.Listlatency = 0, 0, 0 r.Core.ngets, r.Core.nputs, r.Core.nlists = 0, 0, 0 if err == nil { lines = append(lines, string(b)) } // capacity if time.Since(r.timeUpdatedCapacity) >= ctx.config.LRUConfig.CapacityUpdTime { runlru = r.updateCapacity() r.timeUpdatedCapacity = time.Now() for _, mpath := range r.fsmap { fscapacity := r.Capacity[mpath] b, err := json.Marshal(fscapacity) if err == nil { lines = append(lines, mpath+": "+string(b)) } } } // disk riostat := getiostatrunner() if riostat != nil { riostat.Lock() r.CPUidle = riostat.CPUidle for k, v := range riostat.Disk { r.Disk[k] = v // copy b, err := json.Marshal(r.Disk[k]) if err == nil { lines = append(lines, k+": "+string(b)) } } lines = append(lines, fmt.Sprintf("CPU idle: %s%%", r.CPUidle)) riostat.Unlock() } r.Core.logged = true r.Unlock() // log for _, ln := range lines { glog.Infoln(ln) } return } func (r *storstatsrunner) housekeep(runlru bool) { t := gettarget() if runlru && ctx.config.LRUConfig.LRUEnabled { go t.runLRU() } // Run prefetch operation if there are items to be prefetched if len(t.prefetchQueue) > 0 { go t.doPrefetch() } // keep total log size below the configured max if time.Since(r.timeCheckedLogSizes) >= logsTotalSizeCheckTime { go r.removeLogs(ctx.config.Log.MaxTotal) r.timeCheckedLogSizes = time.Now() } } func (r *storstatsrunner) removeLogs(maxtotal uint64) { var ( tot int64 infos = []os.FileInfo{} ) logfinfos, err := ioutil.ReadDir(ctx.config.Log.Dir) if err != nil { glog.Errorf("GC logs: cannot read log dir %s, err: %v", ctx.config.Log.Dir, err) return // ignore error } // sample name dfc.ip-10-0-2-19.root.log.INFO.20180404-031540.2249 for _, logfi := range logfinfos { if logfi.IsDir() { continue } if !strings.HasPrefix(logfi.Name(), "dfc.") { continue } if !strings.Contains(logfi.Name(), ".log.") { continue } tot += logfi.Size() if strings.Contains(logfi.Name(), ".INFO.") { // GC "INFO" logs only infos = append(infos, logfi) } } if tot < int64(maxtotal) { return } if len(infos) <= 1 { glog.Errorf("GC logs err: log dir %s, total %d, maxtotal %d", ctx.config.Log.Dir, tot, maxtotal) return } r.removeOlderLogs(tot, int64(maxtotal), infos) } func (r *storstatsrunner) removeOlderLogs(tot, maxtotal int64, filteredInfos []os.FileInfo) { fiLess := func(i, j int) bool { return filteredInfos[i].ModTime().Before(filteredInfos[j].ModTime()) } if glog.V(3) { glog.Infof("GC logs: started") } sort.Slice(filteredInfos, fiLess) for _, logfi := range filteredInfos[:len(filteredInfos)-1] { // except last = current logfqn := ctx.config.Log.Dir + "/" + logfi.Name() if err := os.Remove(logfqn); err == nil { tot -= logfi.Size() glog.Infof("GC logs: removed %s", logfqn) if tot < maxtotal { break } } else { glog.Errorf("GC logs: failed to remove %s", logfqn) } } if glog.V(3) { glog.Infof("GC logs: done") } } func (r *storstatsrunner) updateCapacity() (runlru bool) { for _, mpath := range r.fsmap { statfs := &syscall.Statfs_t{} if err := syscall.Statfs(mpath, statfs); err != nil { glog.Errorf("Failed to statfs mp %q, err: %v", mpath, err) continue } fscapacity := r.Capacity[mpath] r.fillfscap(fscapacity, statfs) if fscapacity.Usedpct >= ctx.config.LRUConfig.HighWM { runlru = true } } return } func (r *storstatsrunner) fillfscap(fscapacity *fscapacity, statfs *syscall.Statfs_t) { fscapacity.Used = (statfs.Blocks - statfs.Bavail) * uint64(statfs.Bsize) fscapacity.Avail = statfs.Bavail * uint64(statfs.Bsize) fscapacity.Usedpct = uint32((statfs.Blocks - statfs.Bavail) * 100 / statfs.Blocks) } func (r *storstatsrunner) init() { r.Disk = make(map[string]deviometrics, 8) // local filesystems and their cap-s r.Capacity = make(map[string]*fscapacity) r.fsmap = make(map[syscall.Fsid]string) for mpath, mountpath := range ctx.mountpaths.available { mp1, ok := r.fsmap[mountpath.Fsid] if ok { // the same filesystem: usage cannot be different.. assert(r.Capacity[mp1] != nil) r.Capacity[mpath] = r.Capacity[mp1] continue } statfs := &syscall.Statfs_t{} if err := syscall.Statfs(mpath, statfs); err != nil { glog.Errorf("Failed to statfs mp %q, err: %v", mpath, err) continue } r.fsmap[mountpath.Fsid] = mpath r.Capacity[mpath] = &fscapacity{} r.fillfscap(r.Capacity[mpath], statfs) } } func (r *storstatsrunner) add(name string, val int64) { r.Lock() r.addLocked(name, val) r.Unlock() } // FIXME: copy paste func (r *storstatsrunner) addMany(nameval ...interface{}) { r.Lock() defer r.Unlock() i := 0 for i < len(nameval) { statsname, ok := nameval[i].(string) assert(ok, fmt.Sprintf("Invalid stats name: %v, %T", nameval[i], nameval[i])) i++ statsval, ok := nameval[i].(int64) assert(ok, fmt.Sprintf("Invalid stats type: %v, %T", nameval[i], nameval[i])) i++ r.addLocked(statsname, statsval) } } func (r *storstatsrunner) addLocked(name string, val int64) { var v *int64 s := &r.Core switch name { // common case "numget": v = &s.Numget case "numput": v = &s.Numput case "numpost": v = &s.Numpost case "numdelete": v = &s.Numdelete case "numrename": v = &s.Numrename case "numlist": v = &s.Numlist case "getlatency": v = &s.Getlatency s.ngets++ case "putlatency": v = &s.Putlatency s.nputs++ case "listlatency": v = &s.Listlatency s.nlists++ case "numerr": v = &s.Numerr // target only case "numcoldget": v = &s.Numcoldget case "bytesloaded": v = &s.Bytesloaded case "bytesevicted": v = &s.Bytesevicted case "filesevicted": v = &s.Filesevicted case "numsentfiles": v = &s.Numsentfiles case "numsentbytes": v = &s.Numsentbytes case "numrecvfiles": v = &s.Numrecvfiles case "numrecvbytes": v = &s.Numrecvbytes case "numprefetch": v = &s.Numprefetch case "bytesprefetched": v = &s.Bytesprefetched case "numvchanged": v = &s.Numvchanged case "bytesvchanged": v = &s.Bytesvchanged case "numbadchecksum": v = &s.Numbadchecksum case "bytesbadchecksum": v = &s.Bytesbadchecksum default: assert(false, "Invalid stats name "+name) } *v += val s.logged = false }
{ targets := make(map[string]*storstatsrunner, ctx.smap.count()) for _, si := range ctx.smap.Smap { targets[si.DaemonID] = &storstatsrunner{Capacity: make(map[string]*fscapacity)} } return &ClusterStats{Target: targets} }
MemoryRuns.py
# -*- coding: utf-8 -*- """ Created on Wed Oct 23 14:16:27 2013 @author: Lucio
""" import os import time import sys import simpactpurple from memory_profiler import profile @profile def run_single(pop): s = simpactpurple.Community() s.INITIAL_POPULATION = pop #Simulate a run of the simulation s.start() # initialize data structures #a few timesteps s.update_recruiting(s.RECRUIT_INITIAL) for i in range(s.RECRUIT_WARM_UP): s.time = i s.time_operator.step() # 1. Time progresses s.relationship_operator.step() # 2. Form and dissolve relationships s.infection_operator.step() # 3. HIV transmission s.update_recruiting(s.RECRUIT_RATE) for i in range(s.RECRUIT_WARM_UP, int(s.NUMBER_OF_YEARS*52)): s.time = i s.time_operator.step() # 1. Time progresses s.relationship_operator.step() # 2. Form and dissolve relationships s.infection_operator.step() # 3. HIV transmission #post-process / clean-up for pipe in s.pipes.values(): pipe.send("terminate") if __name__ == '__main__': run_single(int(sys.argv[1]))
Program for assessing the memory footprint of the simulation. Needs the memory_profiler module (installed on the milano cluster).
benchmarks.rs
#[macro_use] extern crate criterion; extern crate easy_reader; use std::fs::File; use criterion::Criterion; use easy_reader::EasyReader; fn
(c: &mut Criterion) { c.bench_function("build_index", |b| b.iter(|| { let file = File::open("resources/fatty_lipsum_lf").unwrap(); let mut reader = EasyReader::new(file).unwrap(); reader.build_index().unwrap(); })); let file = File::open("resources/fatty_lipsum_lf").unwrap(); let mut reader = EasyReader::new(file).unwrap(); reader.build_index().unwrap(); c.bench_function( "Random lines [1000][index]", move |b| b.iter(|| { for _i in 0..1000 { reader.random_line().unwrap().unwrap(); } }), ); c.bench_function( "Random lines [1000][no_index]", |b| b.iter(|| { let file = File::open("resources/fatty_lipsum_lf").unwrap(); let mut reader = EasyReader::new(file).unwrap(); for _i in 0..1000 { reader.random_line().unwrap().unwrap(); } }), ); let file = File::open("resources/fatty_lipsum_lf").unwrap(); let mut reader = EasyReader::new(file).unwrap(); reader.build_index().unwrap(); c.bench_function( "Read backward [1000][index]", move |b| b.iter(|| { reader.from_eof(); while let Ok(Some(_line)) = reader.prev_line() {} }), ); c.bench_function( "Read backward [1000][no-index]", move |b| b.iter(|| { let file = File::open("resources/fatty_lipsum_lf").unwrap(); let mut reader = EasyReader::new(file).unwrap(); while let Ok(Some(_line)) = reader.prev_line() {} }), ); let file = File::open("resources/fatty_lipsum_lf").unwrap(); let mut reader = EasyReader::new(file).unwrap(); reader.build_index().unwrap(); c.bench_function( "Read forward [EasyReader][index]", move |b| b.iter(|| { while let Ok(Some(_line)) = reader.next_line() {} reader.from_bof(); }), ); c.bench_function( "Read forward [EasyReader][no_index]", move |b| b.iter(|| { let file = File::open("resources/fatty_lipsum_lf").unwrap(); let mut reader = EasyReader::new(file).unwrap(); while let Ok(Some(_line)) = reader.next_line() {} }), ); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
criterion_benchmark
models.go
package sql // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "encoding/json" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/date" "github.com/Azure/go-autorest/autorest/to" "github.com/Azure/go-autorest/tracing" "github.com/satori/go.uuid" "net/http" ) // The package's fully qualified name. const fqdn = "github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/2018-06-15-preview/sql" // AuthenticationType enumerates the values for authentication type. type AuthenticationType string const ( // ADPassword ... ADPassword AuthenticationType = "ADPassword" // SQL ... SQL AuthenticationType = "SQL" ) // PossibleAuthenticationTypeValues returns an array of possible values for the AuthenticationType const type. func PossibleAuthenticationTypeValues() []AuthenticationType { return []AuthenticationType{ADPassword, SQL} } // AutomaticTuningDisabledReason enumerates the values for automatic tuning disabled reason. type AutomaticTuningDisabledReason string const ( // AutoConfigured ... AutoConfigured AutomaticTuningDisabledReason = "AutoConfigured" // Default ... Default AutomaticTuningDisabledReason = "Default" // Disabled ... Disabled AutomaticTuningDisabledReason = "Disabled" // InheritedFromServer ... InheritedFromServer AutomaticTuningDisabledReason = "InheritedFromServer" // NotSupported ... NotSupported AutomaticTuningDisabledReason = "NotSupported" // QueryStoreOff ... QueryStoreOff AutomaticTuningDisabledReason = "QueryStoreOff" // QueryStoreReadOnly ... QueryStoreReadOnly AutomaticTuningDisabledReason = "QueryStoreReadOnly" ) // PossibleAutomaticTuningDisabledReasonValues returns an array of possible values for the AutomaticTuningDisabledReason const type. func PossibleAutomaticTuningDisabledReasonValues() []AutomaticTuningDisabledReason { return []AutomaticTuningDisabledReason{AutoConfigured, Default, Disabled, InheritedFromServer, NotSupported, QueryStoreOff, QueryStoreReadOnly} } // AutomaticTuningMode enumerates the values for automatic tuning mode. type AutomaticTuningMode string const ( // Auto ... Auto AutomaticTuningMode = "Auto" // Custom ... Custom AutomaticTuningMode = "Custom" // Inherit ... Inherit AutomaticTuningMode = "Inherit" // Unspecified ... Unspecified AutomaticTuningMode = "Unspecified" ) // PossibleAutomaticTuningModeValues returns an array of possible values for the AutomaticTuningMode const type. func PossibleAutomaticTuningModeValues() []AutomaticTuningMode { return []AutomaticTuningMode{Auto, Custom, Inherit, Unspecified} } // AutomaticTuningOptionModeActual enumerates the values for automatic tuning option mode actual. type AutomaticTuningOptionModeActual string const ( // Off ... Off AutomaticTuningOptionModeActual = "Off" // On ... On AutomaticTuningOptionModeActual = "On" ) // PossibleAutomaticTuningOptionModeActualValues returns an array of possible values for the AutomaticTuningOptionModeActual const type. func PossibleAutomaticTuningOptionModeActualValues() []AutomaticTuningOptionModeActual { return []AutomaticTuningOptionModeActual{Off, On} } // AutomaticTuningOptionModeDesired enumerates the values for automatic tuning option mode desired. type AutomaticTuningOptionModeDesired string const ( // AutomaticTuningOptionModeDesiredDefault ... AutomaticTuningOptionModeDesiredDefault AutomaticTuningOptionModeDesired = "Default" // AutomaticTuningOptionModeDesiredOff ... AutomaticTuningOptionModeDesiredOff AutomaticTuningOptionModeDesired = "Off" // AutomaticTuningOptionModeDesiredOn ... AutomaticTuningOptionModeDesiredOn AutomaticTuningOptionModeDesired = "On" ) // PossibleAutomaticTuningOptionModeDesiredValues returns an array of possible values for the AutomaticTuningOptionModeDesired const type. func PossibleAutomaticTuningOptionModeDesiredValues() []AutomaticTuningOptionModeDesired { return []AutomaticTuningOptionModeDesired{AutomaticTuningOptionModeDesiredDefault, AutomaticTuningOptionModeDesiredOff, AutomaticTuningOptionModeDesiredOn} } // AutomaticTuningServerMode enumerates the values for automatic tuning server mode. type AutomaticTuningServerMode string const ( // AutomaticTuningServerModeAuto ... AutomaticTuningServerModeAuto AutomaticTuningServerMode = "Auto" // AutomaticTuningServerModeCustom ... AutomaticTuningServerModeCustom AutomaticTuningServerMode = "Custom" // AutomaticTuningServerModeUnspecified ... AutomaticTuningServerModeUnspecified AutomaticTuningServerMode = "Unspecified" ) // PossibleAutomaticTuningServerModeValues returns an array of possible values for the AutomaticTuningServerMode const type. func PossibleAutomaticTuningServerModeValues() []AutomaticTuningServerMode { return []AutomaticTuningServerMode{AutomaticTuningServerModeAuto, AutomaticTuningServerModeCustom, AutomaticTuningServerModeUnspecified} } // AutomaticTuningServerReason enumerates the values for automatic tuning server reason. type AutomaticTuningServerReason string const ( // AutomaticTuningServerReasonAutoConfigured ... AutomaticTuningServerReasonAutoConfigured AutomaticTuningServerReason = "AutoConfigured" // AutomaticTuningServerReasonDefault ... AutomaticTuningServerReasonDefault AutomaticTuningServerReason = "Default" // AutomaticTuningServerReasonDisabled ... AutomaticTuningServerReasonDisabled AutomaticTuningServerReason = "Disabled" ) // PossibleAutomaticTuningServerReasonValues returns an array of possible values for the AutomaticTuningServerReason const type. func PossibleAutomaticTuningServerReasonValues() []AutomaticTuningServerReason { return []AutomaticTuningServerReason{AutomaticTuningServerReasonAutoConfigured, AutomaticTuningServerReasonDefault, AutomaticTuningServerReasonDisabled} } // BlobAuditingPolicyState enumerates the values for blob auditing policy state. type BlobAuditingPolicyState string const ( // BlobAuditingPolicyStateDisabled ... BlobAuditingPolicyStateDisabled BlobAuditingPolicyState = "Disabled" // BlobAuditingPolicyStateEnabled ... BlobAuditingPolicyStateEnabled BlobAuditingPolicyState = "Enabled" ) // PossibleBlobAuditingPolicyStateValues returns an array of possible values for the BlobAuditingPolicyState const type. func PossibleBlobAuditingPolicyStateValues() []BlobAuditingPolicyState { return []BlobAuditingPolicyState{BlobAuditingPolicyStateDisabled, BlobAuditingPolicyStateEnabled} } // CapabilityGroup enumerates the values for capability group. type CapabilityGroup string const ( // SupportedEditions ... SupportedEditions CapabilityGroup = "supportedEditions" // SupportedElasticPoolEditions ... SupportedElasticPoolEditions CapabilityGroup = "supportedElasticPoolEditions" // SupportedManagedInstanceVersions ... SupportedManagedInstanceVersions CapabilityGroup = "supportedManagedInstanceVersions" ) // PossibleCapabilityGroupValues returns an array of possible values for the CapabilityGroup const type. func PossibleCapabilityGroupValues() []CapabilityGroup { return []CapabilityGroup{SupportedEditions, SupportedElasticPoolEditions, SupportedManagedInstanceVersions} } // CapabilityStatus enumerates the values for capability status. type CapabilityStatus string const ( // CapabilityStatusAvailable ... CapabilityStatusAvailable CapabilityStatus = "Available" // CapabilityStatusDefault ... CapabilityStatusDefault CapabilityStatus = "Default" // CapabilityStatusDisabled ... CapabilityStatusDisabled CapabilityStatus = "Disabled" // CapabilityStatusVisible ... CapabilityStatusVisible CapabilityStatus = "Visible" ) // PossibleCapabilityStatusValues returns an array of possible values for the CapabilityStatus const type. func PossibleCapabilityStatusValues() []CapabilityStatus { return []CapabilityStatus{CapabilityStatusAvailable, CapabilityStatusDefault, CapabilityStatusDisabled, CapabilityStatusVisible} } // CatalogCollationType enumerates the values for catalog collation type. type CatalogCollationType string const ( // DATABASEDEFAULT ... DATABASEDEFAULT CatalogCollationType = "DATABASE_DEFAULT" // SQLLatin1GeneralCP1CIAS ... SQLLatin1GeneralCP1CIAS CatalogCollationType = "SQL_Latin1_General_CP1_CI_AS" ) // PossibleCatalogCollationTypeValues returns an array of possible values for the CatalogCollationType const type. func PossibleCatalogCollationTypeValues() []CatalogCollationType { return []CatalogCollationType{DATABASEDEFAULT, SQLLatin1GeneralCP1CIAS} } // CheckNameAvailabilityReason enumerates the values for check name availability reason. type CheckNameAvailabilityReason string const ( // AlreadyExists ... AlreadyExists CheckNameAvailabilityReason = "AlreadyExists" // Invalid ... Invalid CheckNameAvailabilityReason = "Invalid" ) // PossibleCheckNameAvailabilityReasonValues returns an array of possible values for the CheckNameAvailabilityReason const type. func PossibleCheckNameAvailabilityReasonValues() []CheckNameAvailabilityReason { return []CheckNameAvailabilityReason{AlreadyExists, Invalid} } // CreateMode enumerates the values for create mode. type CreateMode string const ( // CreateModeCopy ... CreateModeCopy CreateMode = "Copy" // CreateModeDefault ... CreateModeDefault CreateMode = "Default" // CreateModeOnlineSecondary ... CreateModeOnlineSecondary CreateMode = "OnlineSecondary" // CreateModePointInTimeRestore ... CreateModePointInTimeRestore CreateMode = "PointInTimeRestore" // CreateModeRecovery ... CreateModeRecovery CreateMode = "Recovery" // CreateModeRestore ... CreateModeRestore CreateMode = "Restore" // CreateModeRestoreExternalBackup ... CreateModeRestoreExternalBackup CreateMode = "RestoreExternalBackup" // CreateModeRestoreExternalBackupSecondary ... CreateModeRestoreExternalBackupSecondary CreateMode = "RestoreExternalBackupSecondary" // CreateModeRestoreLongTermRetentionBackup ... CreateModeRestoreLongTermRetentionBackup CreateMode = "RestoreLongTermRetentionBackup" // CreateModeSecondary ... CreateModeSecondary CreateMode = "Secondary" ) // PossibleCreateModeValues returns an array of possible values for the CreateMode const type. func PossibleCreateModeValues() []CreateMode { return []CreateMode{CreateModeCopy, CreateModeDefault, CreateModeOnlineSecondary, CreateModePointInTimeRestore, CreateModeRecovery, CreateModeRestore, CreateModeRestoreExternalBackup, CreateModeRestoreExternalBackupSecondary, CreateModeRestoreLongTermRetentionBackup, CreateModeSecondary} } // DatabaseEdition enumerates the values for database edition. type DatabaseEdition string const ( // Basic ... Basic DatabaseEdition = "Basic" // Business ... Business DatabaseEdition = "Business" // BusinessCritical ... BusinessCritical DatabaseEdition = "BusinessCritical" // DataWarehouse ... DataWarehouse DatabaseEdition = "DataWarehouse" // Free ... Free DatabaseEdition = "Free" // GeneralPurpose ... GeneralPurpose DatabaseEdition = "GeneralPurpose" // Hyperscale ... Hyperscale DatabaseEdition = "Hyperscale" // Premium ... Premium DatabaseEdition = "Premium" // PremiumRS ... PremiumRS DatabaseEdition = "PremiumRS" // Standard ... Standard DatabaseEdition = "Standard" // Stretch ... Stretch DatabaseEdition = "Stretch" // System ... System DatabaseEdition = "System" // System2 ... System2 DatabaseEdition = "System2" // Web ... Web DatabaseEdition = "Web" ) // PossibleDatabaseEditionValues returns an array of possible values for the DatabaseEdition const type. func PossibleDatabaseEditionValues() []DatabaseEdition { return []DatabaseEdition{Basic, Business, BusinessCritical, DataWarehouse, Free, GeneralPurpose, Hyperscale, Premium, PremiumRS, Standard, Stretch, System, System2, Web} } // DatabaseLicenseType enumerates the values for database license type. type DatabaseLicenseType string const ( // BasePrice ... BasePrice DatabaseLicenseType = "BasePrice" // LicenseIncluded ... LicenseIncluded DatabaseLicenseType = "LicenseIncluded" ) // PossibleDatabaseLicenseTypeValues returns an array of possible values for the DatabaseLicenseType const type. func PossibleDatabaseLicenseTypeValues() []DatabaseLicenseType { return []DatabaseLicenseType{BasePrice, LicenseIncluded} } // DatabaseReadScale enumerates the values for database read scale. type DatabaseReadScale string const ( // DatabaseReadScaleDisabled ... DatabaseReadScaleDisabled DatabaseReadScale = "Disabled" // DatabaseReadScaleEnabled ... DatabaseReadScaleEnabled DatabaseReadScale = "Enabled" ) // PossibleDatabaseReadScaleValues returns an array of possible values for the DatabaseReadScale const type. func PossibleDatabaseReadScaleValues() []DatabaseReadScale { return []DatabaseReadScale{DatabaseReadScaleDisabled, DatabaseReadScaleEnabled} } // DatabaseStatus enumerates the values for database status. type DatabaseStatus string const ( // DatabaseStatusAutoClosed ... DatabaseStatusAutoClosed DatabaseStatus = "AutoClosed" // DatabaseStatusCopying ... DatabaseStatusCopying DatabaseStatus = "Copying" // DatabaseStatusCreating ... DatabaseStatusCreating DatabaseStatus = "Creating" // DatabaseStatusDisabled ... DatabaseStatusDisabled DatabaseStatus = "Disabled" // DatabaseStatusEmergencyMode ... DatabaseStatusEmergencyMode DatabaseStatus = "EmergencyMode" // DatabaseStatusInaccessible ... DatabaseStatusInaccessible DatabaseStatus = "Inaccessible" // DatabaseStatusOffline ... DatabaseStatusOffline DatabaseStatus = "Offline" // DatabaseStatusOfflineChangingDwPerformanceTiers ... DatabaseStatusOfflineChangingDwPerformanceTiers DatabaseStatus = "OfflineChangingDwPerformanceTiers" // DatabaseStatusOfflineSecondary ... DatabaseStatusOfflineSecondary DatabaseStatus = "OfflineSecondary" // DatabaseStatusOnline ... DatabaseStatusOnline DatabaseStatus = "Online" // DatabaseStatusOnlineChangingDwPerformanceTiers ... DatabaseStatusOnlineChangingDwPerformanceTiers DatabaseStatus = "OnlineChangingDwPerformanceTiers" // DatabaseStatusPaused ... DatabaseStatusPaused DatabaseStatus = "Paused" // DatabaseStatusPausing ... DatabaseStatusPausing DatabaseStatus = "Pausing" // DatabaseStatusRecovering ... DatabaseStatusRecovering DatabaseStatus = "Recovering" // DatabaseStatusRecoveryPending ... DatabaseStatusRecoveryPending DatabaseStatus = "RecoveryPending" // DatabaseStatusRestoring ... DatabaseStatusRestoring DatabaseStatus = "Restoring" // DatabaseStatusResuming ... DatabaseStatusResuming DatabaseStatus = "Resuming" // DatabaseStatusScaling ... DatabaseStatusScaling DatabaseStatus = "Scaling" // DatabaseStatusShutdown ... DatabaseStatusShutdown DatabaseStatus = "Shutdown" // DatabaseStatusStandby ... DatabaseStatusStandby DatabaseStatus = "Standby" // DatabaseStatusSuspect ... DatabaseStatusSuspect DatabaseStatus = "Suspect" ) // PossibleDatabaseStatusValues returns an array of possible values for the DatabaseStatus const type. func PossibleDatabaseStatusValues() []DatabaseStatus { return []DatabaseStatus{DatabaseStatusAutoClosed, DatabaseStatusCopying, DatabaseStatusCreating, DatabaseStatusDisabled, DatabaseStatusEmergencyMode, DatabaseStatusInaccessible, DatabaseStatusOffline, DatabaseStatusOfflineChangingDwPerformanceTiers, DatabaseStatusOfflineSecondary, DatabaseStatusOnline, DatabaseStatusOnlineChangingDwPerformanceTiers, DatabaseStatusPaused, DatabaseStatusPausing, DatabaseStatusRecovering, DatabaseStatusRecoveryPending, DatabaseStatusRestoring, DatabaseStatusResuming, DatabaseStatusScaling, DatabaseStatusShutdown, DatabaseStatusStandby, DatabaseStatusSuspect} } // DataMaskingFunction enumerates the values for data masking function. type DataMaskingFunction string const ( // DataMaskingFunctionCCN ... DataMaskingFunctionCCN DataMaskingFunction = "CCN" // DataMaskingFunctionDefault ... DataMaskingFunctionDefault DataMaskingFunction = "Default" // DataMaskingFunctionEmail ... DataMaskingFunctionEmail DataMaskingFunction = "Email" // DataMaskingFunctionNumber ... DataMaskingFunctionNumber DataMaskingFunction = "Number" // DataMaskingFunctionSSN ... DataMaskingFunctionSSN DataMaskingFunction = "SSN" // DataMaskingFunctionText ... DataMaskingFunctionText DataMaskingFunction = "Text" ) // PossibleDataMaskingFunctionValues returns an array of possible values for the DataMaskingFunction const type. func PossibleDataMaskingFunctionValues() []DataMaskingFunction { return []DataMaskingFunction{DataMaskingFunctionCCN, DataMaskingFunctionDefault, DataMaskingFunctionEmail, DataMaskingFunctionNumber, DataMaskingFunctionSSN, DataMaskingFunctionText} } // DataMaskingRuleState enumerates the values for data masking rule state. type DataMaskingRuleState string const ( // DataMaskingRuleStateDisabled ... DataMaskingRuleStateDisabled DataMaskingRuleState = "Disabled" // DataMaskingRuleStateEnabled ... DataMaskingRuleStateEnabled DataMaskingRuleState = "Enabled" ) // PossibleDataMaskingRuleStateValues returns an array of possible values for the DataMaskingRuleState const type. func PossibleDataMaskingRuleStateValues() []DataMaskingRuleState { return []DataMaskingRuleState{DataMaskingRuleStateDisabled, DataMaskingRuleStateEnabled} } // DataMaskingState enumerates the values for data masking state. type DataMaskingState string const ( // DataMaskingStateDisabled ... DataMaskingStateDisabled DataMaskingState = "Disabled" // DataMaskingStateEnabled ... DataMaskingStateEnabled DataMaskingState = "Enabled" ) // PossibleDataMaskingStateValues returns an array of possible values for the DataMaskingState const type. func PossibleDataMaskingStateValues() []DataMaskingState { return []DataMaskingState{DataMaskingStateDisabled, DataMaskingStateEnabled} } // ElasticPoolEdition enumerates the values for elastic pool edition. type ElasticPoolEdition string const ( // ElasticPoolEditionBasic ... ElasticPoolEditionBasic ElasticPoolEdition = "Basic" // ElasticPoolEditionBusinessCritical ... ElasticPoolEditionBusinessCritical ElasticPoolEdition = "BusinessCritical" // ElasticPoolEditionGeneralPurpose ... ElasticPoolEditionGeneralPurpose ElasticPoolEdition = "GeneralPurpose" // ElasticPoolEditionPremium ... ElasticPoolEditionPremium ElasticPoolEdition = "Premium" // ElasticPoolEditionStandard ... ElasticPoolEditionStandard ElasticPoolEdition = "Standard" ) // PossibleElasticPoolEditionValues returns an array of possible values for the ElasticPoolEdition const type. func PossibleElasticPoolEditionValues() []ElasticPoolEdition { return []ElasticPoolEdition{ElasticPoolEditionBasic, ElasticPoolEditionBusinessCritical, ElasticPoolEditionGeneralPurpose, ElasticPoolEditionPremium, ElasticPoolEditionStandard} } // ElasticPoolLicenseType enumerates the values for elastic pool license type. type ElasticPoolLicenseType string const ( // ElasticPoolLicenseTypeBasePrice ... ElasticPoolLicenseTypeBasePrice ElasticPoolLicenseType = "BasePrice" // ElasticPoolLicenseTypeLicenseIncluded ... ElasticPoolLicenseTypeLicenseIncluded ElasticPoolLicenseType = "LicenseIncluded" ) // PossibleElasticPoolLicenseTypeValues returns an array of possible values for the ElasticPoolLicenseType const type. func PossibleElasticPoolLicenseTypeValues() []ElasticPoolLicenseType { return []ElasticPoolLicenseType{ElasticPoolLicenseTypeBasePrice, ElasticPoolLicenseTypeLicenseIncluded} } // ElasticPoolState enumerates the values for elastic pool state. type ElasticPoolState string const ( // ElasticPoolStateCreating ... ElasticPoolStateCreating ElasticPoolState = "Creating" // ElasticPoolStateDisabled ... ElasticPoolStateDisabled ElasticPoolState = "Disabled" // ElasticPoolStateReady ... ElasticPoolStateReady ElasticPoolState = "Ready" ) // PossibleElasticPoolStateValues returns an array of possible values for the ElasticPoolState const type. func PossibleElasticPoolStateValues() []ElasticPoolState { return []ElasticPoolState{ElasticPoolStateCreating, ElasticPoolStateDisabled, ElasticPoolStateReady} } // FailoverGroupReplicationRole enumerates the values for failover group replication role. type FailoverGroupReplicationRole string const ( // Primary ... Primary FailoverGroupReplicationRole = "Primary" // Secondary ... Secondary FailoverGroupReplicationRole = "Secondary" ) // PossibleFailoverGroupReplicationRoleValues returns an array of possible values for the FailoverGroupReplicationRole const type. func PossibleFailoverGroupReplicationRoleValues() []FailoverGroupReplicationRole { return []FailoverGroupReplicationRole{Primary, Secondary} } // GeoBackupPolicyState enumerates the values for geo backup policy state. type GeoBackupPolicyState string const ( // GeoBackupPolicyStateDisabled ... GeoBackupPolicyStateDisabled GeoBackupPolicyState = "Disabled" // GeoBackupPolicyStateEnabled ... GeoBackupPolicyStateEnabled GeoBackupPolicyState = "Enabled" ) // PossibleGeoBackupPolicyStateValues returns an array of possible values for the GeoBackupPolicyState const type. func PossibleGeoBackupPolicyStateValues() []GeoBackupPolicyState { return []GeoBackupPolicyState{GeoBackupPolicyStateDisabled, GeoBackupPolicyStateEnabled} } // IdentityType enumerates the values for identity type. type IdentityType string const ( // SystemAssigned ... SystemAssigned IdentityType = "SystemAssigned" ) // PossibleIdentityTypeValues returns an array of possible values for the IdentityType const type. func PossibleIdentityTypeValues() []IdentityType { return []IdentityType{SystemAssigned} } // InstanceFailoverGroupReplicationRole enumerates the values for instance failover group replication role. type InstanceFailoverGroupReplicationRole string const ( // InstanceFailoverGroupReplicationRolePrimary ... InstanceFailoverGroupReplicationRolePrimary InstanceFailoverGroupReplicationRole = "Primary" // InstanceFailoverGroupReplicationRoleSecondary ... InstanceFailoverGroupReplicationRoleSecondary InstanceFailoverGroupReplicationRole = "Secondary" ) // PossibleInstanceFailoverGroupReplicationRoleValues returns an array of possible values for the InstanceFailoverGroupReplicationRole const type. func PossibleInstanceFailoverGroupReplicationRoleValues() []InstanceFailoverGroupReplicationRole { return []InstanceFailoverGroupReplicationRole{InstanceFailoverGroupReplicationRolePrimary, InstanceFailoverGroupReplicationRoleSecondary} } // InstancePoolLicenseType enumerates the values for instance pool license type. type InstancePoolLicenseType string const ( // InstancePoolLicenseTypeBasePrice ... InstancePoolLicenseTypeBasePrice InstancePoolLicenseType = "BasePrice" // InstancePoolLicenseTypeLicenseIncluded ... InstancePoolLicenseTypeLicenseIncluded InstancePoolLicenseType = "LicenseIncluded" ) // PossibleInstancePoolLicenseTypeValues returns an array of possible values for the InstancePoolLicenseType const type. func PossibleInstancePoolLicenseTypeValues() []InstancePoolLicenseType { return []InstancePoolLicenseType{InstancePoolLicenseTypeBasePrice, InstancePoolLicenseTypeLicenseIncluded} } // JobAgentState enumerates the values for job agent state. type JobAgentState string const ( // JobAgentStateCreating ... JobAgentStateCreating JobAgentState = "Creating" // JobAgentStateDeleting ... JobAgentStateDeleting JobAgentState = "Deleting" // JobAgentStateDisabled ... JobAgentStateDisabled JobAgentState = "Disabled" // JobAgentStateReady ... JobAgentStateReady JobAgentState = "Ready" // JobAgentStateUpdating ... JobAgentStateUpdating JobAgentState = "Updating" ) // PossibleJobAgentStateValues returns an array of possible values for the JobAgentState const type. func PossibleJobAgentStateValues() []JobAgentState { return []JobAgentState{JobAgentStateCreating, JobAgentStateDeleting, JobAgentStateDisabled, JobAgentStateReady, JobAgentStateUpdating} } // JobExecutionLifecycle enumerates the values for job execution lifecycle. type JobExecutionLifecycle string const ( // Canceled ... Canceled JobExecutionLifecycle = "Canceled" // Created ... Created JobExecutionLifecycle = "Created" // Failed ... Failed JobExecutionLifecycle = "Failed" // InProgress ... InProgress JobExecutionLifecycle = "InProgress" // Skipped ... Skipped JobExecutionLifecycle = "Skipped" // Succeeded ... Succeeded JobExecutionLifecycle = "Succeeded" // SucceededWithSkipped ... SucceededWithSkipped JobExecutionLifecycle = "SucceededWithSkipped" // TimedOut ... TimedOut JobExecutionLifecycle = "TimedOut" // WaitingForChildJobExecutions ... WaitingForChildJobExecutions JobExecutionLifecycle = "WaitingForChildJobExecutions" // WaitingForRetry ... WaitingForRetry JobExecutionLifecycle = "WaitingForRetry" ) // PossibleJobExecutionLifecycleValues returns an array of possible values for the JobExecutionLifecycle const type. func PossibleJobExecutionLifecycleValues() []JobExecutionLifecycle { return []JobExecutionLifecycle{Canceled, Created, Failed, InProgress, Skipped, Succeeded, SucceededWithSkipped, TimedOut, WaitingForChildJobExecutions, WaitingForRetry} } // JobScheduleType enumerates the values for job schedule type. type JobScheduleType string const ( // Once ... Once JobScheduleType = "Once" // Recurring ... Recurring JobScheduleType = "Recurring" ) // PossibleJobScheduleTypeValues returns an array of possible values for the JobScheduleType const type. func PossibleJobScheduleTypeValues() []JobScheduleType { return []JobScheduleType{Once, Recurring} } // JobStepActionSource enumerates the values for job step action source. type JobStepActionSource string const ( // Inline ... Inline JobStepActionSource = "Inline" ) // PossibleJobStepActionSourceValues returns an array of possible values for the JobStepActionSource const type. func PossibleJobStepActionSourceValues() []JobStepActionSource { return []JobStepActionSource{Inline} } // JobStepActionType enumerates the values for job step action type. type JobStepActionType string const ( // TSQL ... TSQL JobStepActionType = "TSql" ) // PossibleJobStepActionTypeValues returns an array of possible values for the JobStepActionType const type. func PossibleJobStepActionTypeValues() []JobStepActionType { return []JobStepActionType{TSQL} } // JobStepOutputType enumerates the values for job step output type. type JobStepOutputType string const ( // SQLDatabase ... SQLDatabase JobStepOutputType = "SqlDatabase" ) // PossibleJobStepOutputTypeValues returns an array of possible values for the JobStepOutputType const type. func
() []JobStepOutputType { return []JobStepOutputType{SQLDatabase} } // JobTargetGroupMembershipType enumerates the values for job target group membership type. type JobTargetGroupMembershipType string const ( // Exclude ... Exclude JobTargetGroupMembershipType = "Exclude" // Include ... Include JobTargetGroupMembershipType = "Include" ) // PossibleJobTargetGroupMembershipTypeValues returns an array of possible values for the JobTargetGroupMembershipType const type. func PossibleJobTargetGroupMembershipTypeValues() []JobTargetGroupMembershipType { return []JobTargetGroupMembershipType{Exclude, Include} } // JobTargetType enumerates the values for job target type. type JobTargetType string const ( // JobTargetTypeSQLDatabase ... JobTargetTypeSQLDatabase JobTargetType = "SqlDatabase" // JobTargetTypeSQLElasticPool ... JobTargetTypeSQLElasticPool JobTargetType = "SqlElasticPool" // JobTargetTypeSQLServer ... JobTargetTypeSQLServer JobTargetType = "SqlServer" // JobTargetTypeSQLShardMap ... JobTargetTypeSQLShardMap JobTargetType = "SqlShardMap" // JobTargetTypeTargetGroup ... JobTargetTypeTargetGroup JobTargetType = "TargetGroup" ) // PossibleJobTargetTypeValues returns an array of possible values for the JobTargetType const type. func PossibleJobTargetTypeValues() []JobTargetType { return []JobTargetType{JobTargetTypeSQLDatabase, JobTargetTypeSQLElasticPool, JobTargetTypeSQLServer, JobTargetTypeSQLShardMap, JobTargetTypeTargetGroup} } // LogSizeUnit enumerates the values for log size unit. type LogSizeUnit string const ( // Gigabytes ... Gigabytes LogSizeUnit = "Gigabytes" // Megabytes ... Megabytes LogSizeUnit = "Megabytes" // Percent ... Percent LogSizeUnit = "Percent" // Petabytes ... Petabytes LogSizeUnit = "Petabytes" // Terabytes ... Terabytes LogSizeUnit = "Terabytes" ) // PossibleLogSizeUnitValues returns an array of possible values for the LogSizeUnit const type. func PossibleLogSizeUnitValues() []LogSizeUnit { return []LogSizeUnit{Gigabytes, Megabytes, Percent, Petabytes, Terabytes} } // LongTermRetentionDatabaseState enumerates the values for long term retention database state. type LongTermRetentionDatabaseState string const ( // All ... All LongTermRetentionDatabaseState = "All" // Deleted ... Deleted LongTermRetentionDatabaseState = "Deleted" // Live ... Live LongTermRetentionDatabaseState = "Live" ) // PossibleLongTermRetentionDatabaseStateValues returns an array of possible values for the LongTermRetentionDatabaseState const type. func PossibleLongTermRetentionDatabaseStateValues() []LongTermRetentionDatabaseState { return []LongTermRetentionDatabaseState{All, Deleted, Live} } // ManagedDatabaseCreateMode enumerates the values for managed database create mode. type ManagedDatabaseCreateMode string const ( // ManagedDatabaseCreateModeDefault ... ManagedDatabaseCreateModeDefault ManagedDatabaseCreateMode = "Default" // ManagedDatabaseCreateModePointInTimeRestore ... ManagedDatabaseCreateModePointInTimeRestore ManagedDatabaseCreateMode = "PointInTimeRestore" // ManagedDatabaseCreateModeRecovery ... ManagedDatabaseCreateModeRecovery ManagedDatabaseCreateMode = "Recovery" // ManagedDatabaseCreateModeRestoreExternalBackup ... ManagedDatabaseCreateModeRestoreExternalBackup ManagedDatabaseCreateMode = "RestoreExternalBackup" ) // PossibleManagedDatabaseCreateModeValues returns an array of possible values for the ManagedDatabaseCreateMode const type. func PossibleManagedDatabaseCreateModeValues() []ManagedDatabaseCreateMode { return []ManagedDatabaseCreateMode{ManagedDatabaseCreateModeDefault, ManagedDatabaseCreateModePointInTimeRestore, ManagedDatabaseCreateModeRecovery, ManagedDatabaseCreateModeRestoreExternalBackup} } // ManagedDatabaseStatus enumerates the values for managed database status. type ManagedDatabaseStatus string const ( // Creating ... Creating ManagedDatabaseStatus = "Creating" // Inaccessible ... Inaccessible ManagedDatabaseStatus = "Inaccessible" // Offline ... Offline ManagedDatabaseStatus = "Offline" // Online ... Online ManagedDatabaseStatus = "Online" // Restoring ... Restoring ManagedDatabaseStatus = "Restoring" // Shutdown ... Shutdown ManagedDatabaseStatus = "Shutdown" // Updating ... Updating ManagedDatabaseStatus = "Updating" ) // PossibleManagedDatabaseStatusValues returns an array of possible values for the ManagedDatabaseStatus const type. func PossibleManagedDatabaseStatusValues() []ManagedDatabaseStatus { return []ManagedDatabaseStatus{Creating, Inaccessible, Offline, Online, Restoring, Shutdown, Updating} } // ManagedInstanceLicenseType enumerates the values for managed instance license type. type ManagedInstanceLicenseType string const ( // ManagedInstanceLicenseTypeBasePrice ... ManagedInstanceLicenseTypeBasePrice ManagedInstanceLicenseType = "BasePrice" // ManagedInstanceLicenseTypeLicenseIncluded ... ManagedInstanceLicenseTypeLicenseIncluded ManagedInstanceLicenseType = "LicenseIncluded" ) // PossibleManagedInstanceLicenseTypeValues returns an array of possible values for the ManagedInstanceLicenseType const type. func PossibleManagedInstanceLicenseTypeValues() []ManagedInstanceLicenseType { return []ManagedInstanceLicenseType{ManagedInstanceLicenseTypeBasePrice, ManagedInstanceLicenseTypeLicenseIncluded} } // ManagedInstanceProxyOverride enumerates the values for managed instance proxy override. type ManagedInstanceProxyOverride string const ( // ManagedInstanceProxyOverrideDefault ... ManagedInstanceProxyOverrideDefault ManagedInstanceProxyOverride = "Default" // ManagedInstanceProxyOverrideProxy ... ManagedInstanceProxyOverrideProxy ManagedInstanceProxyOverride = "Proxy" // ManagedInstanceProxyOverrideRedirect ... ManagedInstanceProxyOverrideRedirect ManagedInstanceProxyOverride = "Redirect" ) // PossibleManagedInstanceProxyOverrideValues returns an array of possible values for the ManagedInstanceProxyOverride const type. func PossibleManagedInstanceProxyOverrideValues() []ManagedInstanceProxyOverride { return []ManagedInstanceProxyOverride{ManagedInstanceProxyOverrideDefault, ManagedInstanceProxyOverrideProxy, ManagedInstanceProxyOverrideRedirect} } // ManagedServerCreateMode enumerates the values for managed server create mode. type ManagedServerCreateMode string const ( // ManagedServerCreateModeDefault ... ManagedServerCreateModeDefault ManagedServerCreateMode = "Default" // ManagedServerCreateModePointInTimeRestore ... ManagedServerCreateModePointInTimeRestore ManagedServerCreateMode = "PointInTimeRestore" ) // PossibleManagedServerCreateModeValues returns an array of possible values for the ManagedServerCreateMode const type. func PossibleManagedServerCreateModeValues() []ManagedServerCreateMode { return []ManagedServerCreateMode{ManagedServerCreateModeDefault, ManagedServerCreateModePointInTimeRestore} } // ManagementOperationState enumerates the values for management operation state. type ManagementOperationState string const ( // ManagementOperationStateCancelInProgress ... ManagementOperationStateCancelInProgress ManagementOperationState = "CancelInProgress" // ManagementOperationStateCancelled ... ManagementOperationStateCancelled ManagementOperationState = "Cancelled" // ManagementOperationStateFailed ... ManagementOperationStateFailed ManagementOperationState = "Failed" // ManagementOperationStateInProgress ... ManagementOperationStateInProgress ManagementOperationState = "InProgress" // ManagementOperationStatePending ... ManagementOperationStatePending ManagementOperationState = "Pending" // ManagementOperationStateSucceeded ... ManagementOperationStateSucceeded ManagementOperationState = "Succeeded" ) // PossibleManagementOperationStateValues returns an array of possible values for the ManagementOperationState const type. func PossibleManagementOperationStateValues() []ManagementOperationState { return []ManagementOperationState{ManagementOperationStateCancelInProgress, ManagementOperationStateCancelled, ManagementOperationStateFailed, ManagementOperationStateInProgress, ManagementOperationStatePending, ManagementOperationStateSucceeded} } // MaxSizeUnit enumerates the values for max size unit. type MaxSizeUnit string const ( // MaxSizeUnitGigabytes ... MaxSizeUnitGigabytes MaxSizeUnit = "Gigabytes" // MaxSizeUnitMegabytes ... MaxSizeUnitMegabytes MaxSizeUnit = "Megabytes" // MaxSizeUnitPetabytes ... MaxSizeUnitPetabytes MaxSizeUnit = "Petabytes" // MaxSizeUnitTerabytes ... MaxSizeUnitTerabytes MaxSizeUnit = "Terabytes" ) // PossibleMaxSizeUnitValues returns an array of possible values for the MaxSizeUnit const type. func PossibleMaxSizeUnitValues() []MaxSizeUnit { return []MaxSizeUnit{MaxSizeUnitGigabytes, MaxSizeUnitMegabytes, MaxSizeUnitPetabytes, MaxSizeUnitTerabytes} } // OperationOrigin enumerates the values for operation origin. type OperationOrigin string const ( // OperationOriginSystem ... OperationOriginSystem OperationOrigin = "system" // OperationOriginUser ... OperationOriginUser OperationOrigin = "user" ) // PossibleOperationOriginValues returns an array of possible values for the OperationOrigin const type. func PossibleOperationOriginValues() []OperationOrigin { return []OperationOrigin{OperationOriginSystem, OperationOriginUser} } // PerformanceLevelUnit enumerates the values for performance level unit. type PerformanceLevelUnit string const ( // DTU ... DTU PerformanceLevelUnit = "DTU" // VCores ... VCores PerformanceLevelUnit = "VCores" ) // PossiblePerformanceLevelUnitValues returns an array of possible values for the PerformanceLevelUnit const type. func PossiblePerformanceLevelUnitValues() []PerformanceLevelUnit { return []PerformanceLevelUnit{DTU, VCores} } // PrimaryAggregationType enumerates the values for primary aggregation type. type PrimaryAggregationType string const ( // Average ... Average PrimaryAggregationType = "Average" // Count ... Count PrimaryAggregationType = "Count" // Maximum ... Maximum PrimaryAggregationType = "Maximum" // Minimum ... Minimum PrimaryAggregationType = "Minimum" // None ... None PrimaryAggregationType = "None" // Total ... Total PrimaryAggregationType = "Total" ) // PossiblePrimaryAggregationTypeValues returns an array of possible values for the PrimaryAggregationType const type. func PossiblePrimaryAggregationTypeValues() []PrimaryAggregationType { return []PrimaryAggregationType{Average, Count, Maximum, Minimum, None, Total} } // ProvisioningState enumerates the values for provisioning state. type ProvisioningState string const ( // ProvisioningStateCanceled ... ProvisioningStateCanceled ProvisioningState = "Canceled" // ProvisioningStateCreated ... ProvisioningStateCreated ProvisioningState = "Created" // ProvisioningStateFailed ... ProvisioningStateFailed ProvisioningState = "Failed" // ProvisioningStateInProgress ... ProvisioningStateInProgress ProvisioningState = "InProgress" // ProvisioningStateSucceeded ... ProvisioningStateSucceeded ProvisioningState = "Succeeded" ) // PossibleProvisioningStateValues returns an array of possible values for the ProvisioningState const type. func PossibleProvisioningStateValues() []ProvisioningState { return []ProvisioningState{ProvisioningStateCanceled, ProvisioningStateCreated, ProvisioningStateFailed, ProvisioningStateInProgress, ProvisioningStateSucceeded} } // ReadOnlyEndpointFailoverPolicy enumerates the values for read only endpoint failover policy. type ReadOnlyEndpointFailoverPolicy string const ( // ReadOnlyEndpointFailoverPolicyDisabled ... ReadOnlyEndpointFailoverPolicyDisabled ReadOnlyEndpointFailoverPolicy = "Disabled" // ReadOnlyEndpointFailoverPolicyEnabled ... ReadOnlyEndpointFailoverPolicyEnabled ReadOnlyEndpointFailoverPolicy = "Enabled" ) // PossibleReadOnlyEndpointFailoverPolicyValues returns an array of possible values for the ReadOnlyEndpointFailoverPolicy const type. func PossibleReadOnlyEndpointFailoverPolicyValues() []ReadOnlyEndpointFailoverPolicy { return []ReadOnlyEndpointFailoverPolicy{ReadOnlyEndpointFailoverPolicyDisabled, ReadOnlyEndpointFailoverPolicyEnabled} } // ReadWriteEndpointFailoverPolicy enumerates the values for read write endpoint failover policy. type ReadWriteEndpointFailoverPolicy string const ( // Automatic ... Automatic ReadWriteEndpointFailoverPolicy = "Automatic" // Manual ... Manual ReadWriteEndpointFailoverPolicy = "Manual" ) // PossibleReadWriteEndpointFailoverPolicyValues returns an array of possible values for the ReadWriteEndpointFailoverPolicy const type. func PossibleReadWriteEndpointFailoverPolicyValues() []ReadWriteEndpointFailoverPolicy { return []ReadWriteEndpointFailoverPolicy{Automatic, Manual} } // RecommendedIndexAction enumerates the values for recommended index action. type RecommendedIndexAction string const ( // Create ... Create RecommendedIndexAction = "Create" // Drop ... Drop RecommendedIndexAction = "Drop" // Rebuild ... Rebuild RecommendedIndexAction = "Rebuild" ) // PossibleRecommendedIndexActionValues returns an array of possible values for the RecommendedIndexAction const type. func PossibleRecommendedIndexActionValues() []RecommendedIndexAction { return []RecommendedIndexAction{Create, Drop, Rebuild} } // RecommendedIndexState enumerates the values for recommended index state. type RecommendedIndexState string const ( // Active ... Active RecommendedIndexState = "Active" // Blocked ... Blocked RecommendedIndexState = "Blocked" // Executing ... Executing RecommendedIndexState = "Executing" // Expired ... Expired RecommendedIndexState = "Expired" // Ignored ... Ignored RecommendedIndexState = "Ignored" // Pending ... Pending RecommendedIndexState = "Pending" // PendingRevert ... PendingRevert RecommendedIndexState = "Pending Revert" // Reverted ... Reverted RecommendedIndexState = "Reverted" // Reverting ... Reverting RecommendedIndexState = "Reverting" // Success ... Success RecommendedIndexState = "Success" // Verifying ... Verifying RecommendedIndexState = "Verifying" ) // PossibleRecommendedIndexStateValues returns an array of possible values for the RecommendedIndexState const type. func PossibleRecommendedIndexStateValues() []RecommendedIndexState { return []RecommendedIndexState{Active, Blocked, Executing, Expired, Ignored, Pending, PendingRevert, Reverted, Reverting, Success, Verifying} } // RecommendedIndexType enumerates the values for recommended index type. type RecommendedIndexType string const ( // CLUSTERED ... CLUSTERED RecommendedIndexType = "CLUSTERED" // CLUSTEREDCOLUMNSTORE ... CLUSTEREDCOLUMNSTORE RecommendedIndexType = "CLUSTERED COLUMNSTORE" // COLUMNSTORE ... COLUMNSTORE RecommendedIndexType = "COLUMNSTORE" // NONCLUSTERED ... NONCLUSTERED RecommendedIndexType = "NONCLUSTERED" ) // PossibleRecommendedIndexTypeValues returns an array of possible values for the RecommendedIndexType const type. func PossibleRecommendedIndexTypeValues() []RecommendedIndexType { return []RecommendedIndexType{CLUSTERED, CLUSTEREDCOLUMNSTORE, COLUMNSTORE, NONCLUSTERED} } // ReplicationRole enumerates the values for replication role. type ReplicationRole string const ( // ReplicationRoleCopy ... ReplicationRoleCopy ReplicationRole = "Copy" // ReplicationRoleNonReadableSecondary ... ReplicationRoleNonReadableSecondary ReplicationRole = "NonReadableSecondary" // ReplicationRolePrimary ... ReplicationRolePrimary ReplicationRole = "Primary" // ReplicationRoleSecondary ... ReplicationRoleSecondary ReplicationRole = "Secondary" // ReplicationRoleSource ... ReplicationRoleSource ReplicationRole = "Source" ) // PossibleReplicationRoleValues returns an array of possible values for the ReplicationRole const type. func PossibleReplicationRoleValues() []ReplicationRole { return []ReplicationRole{ReplicationRoleCopy, ReplicationRoleNonReadableSecondary, ReplicationRolePrimary, ReplicationRoleSecondary, ReplicationRoleSource} } // ReplicationState enumerates the values for replication state. type ReplicationState string const ( // CATCHUP ... CATCHUP ReplicationState = "CATCH_UP" // PENDING ... PENDING ReplicationState = "PENDING" // SEEDING ... SEEDING ReplicationState = "SEEDING" // SUSPENDED ... SUSPENDED ReplicationState = "SUSPENDED" ) // PossibleReplicationStateValues returns an array of possible values for the ReplicationState const type. func PossibleReplicationStateValues() []ReplicationState { return []ReplicationState{CATCHUP, PENDING, SEEDING, SUSPENDED} } // RestorePointType enumerates the values for restore point type. type RestorePointType string const ( // CONTINUOUS ... CONTINUOUS RestorePointType = "CONTINUOUS" // DISCRETE ... DISCRETE RestorePointType = "DISCRETE" ) // PossibleRestorePointTypeValues returns an array of possible values for the RestorePointType const type. func PossibleRestorePointTypeValues() []RestorePointType { return []RestorePointType{CONTINUOUS, DISCRETE} } // SampleName enumerates the values for sample name. type SampleName string const ( // AdventureWorksLT ... AdventureWorksLT SampleName = "AdventureWorksLT" // WideWorldImportersFull ... WideWorldImportersFull SampleName = "WideWorldImportersFull" // WideWorldImportersStd ... WideWorldImportersStd SampleName = "WideWorldImportersStd" ) // PossibleSampleNameValues returns an array of possible values for the SampleName const type. func PossibleSampleNameValues() []SampleName { return []SampleName{AdventureWorksLT, WideWorldImportersFull, WideWorldImportersStd} } // SecurityAlertPolicyEmailAccountAdmins enumerates the values for security alert policy email account admins. type SecurityAlertPolicyEmailAccountAdmins string const ( // SecurityAlertPolicyEmailAccountAdminsDisabled ... SecurityAlertPolicyEmailAccountAdminsDisabled SecurityAlertPolicyEmailAccountAdmins = "Disabled" // SecurityAlertPolicyEmailAccountAdminsEnabled ... SecurityAlertPolicyEmailAccountAdminsEnabled SecurityAlertPolicyEmailAccountAdmins = "Enabled" ) // PossibleSecurityAlertPolicyEmailAccountAdminsValues returns an array of possible values for the SecurityAlertPolicyEmailAccountAdmins const type. func PossibleSecurityAlertPolicyEmailAccountAdminsValues() []SecurityAlertPolicyEmailAccountAdmins { return []SecurityAlertPolicyEmailAccountAdmins{SecurityAlertPolicyEmailAccountAdminsDisabled, SecurityAlertPolicyEmailAccountAdminsEnabled} } // SecurityAlertPolicyState enumerates the values for security alert policy state. type SecurityAlertPolicyState string const ( // SecurityAlertPolicyStateDisabled ... SecurityAlertPolicyStateDisabled SecurityAlertPolicyState = "Disabled" // SecurityAlertPolicyStateEnabled ... SecurityAlertPolicyStateEnabled SecurityAlertPolicyState = "Enabled" // SecurityAlertPolicyStateNew ... SecurityAlertPolicyStateNew SecurityAlertPolicyState = "New" ) // PossibleSecurityAlertPolicyStateValues returns an array of possible values for the SecurityAlertPolicyState const type. func PossibleSecurityAlertPolicyStateValues() []SecurityAlertPolicyState { return []SecurityAlertPolicyState{SecurityAlertPolicyStateDisabled, SecurityAlertPolicyStateEnabled, SecurityAlertPolicyStateNew} } // SecurityAlertPolicyUseServerDefault enumerates the values for security alert policy use server default. type SecurityAlertPolicyUseServerDefault string const ( // SecurityAlertPolicyUseServerDefaultDisabled ... SecurityAlertPolicyUseServerDefaultDisabled SecurityAlertPolicyUseServerDefault = "Disabled" // SecurityAlertPolicyUseServerDefaultEnabled ... SecurityAlertPolicyUseServerDefaultEnabled SecurityAlertPolicyUseServerDefault = "Enabled" ) // PossibleSecurityAlertPolicyUseServerDefaultValues returns an array of possible values for the SecurityAlertPolicyUseServerDefault const type. func PossibleSecurityAlertPolicyUseServerDefaultValues() []SecurityAlertPolicyUseServerDefault { return []SecurityAlertPolicyUseServerDefault{SecurityAlertPolicyUseServerDefaultDisabled, SecurityAlertPolicyUseServerDefaultEnabled} } // SensitivityLabelSource enumerates the values for sensitivity label source. type SensitivityLabelSource string const ( // Current ... Current SensitivityLabelSource = "current" // Recommended ... Recommended SensitivityLabelSource = "recommended" ) // PossibleSensitivityLabelSourceValues returns an array of possible values for the SensitivityLabelSource const type. func PossibleSensitivityLabelSourceValues() []SensitivityLabelSource { return []SensitivityLabelSource{Current, Recommended} } // ServerConnectionType enumerates the values for server connection type. type ServerConnectionType string const ( // ServerConnectionTypeDefault ... ServerConnectionTypeDefault ServerConnectionType = "Default" // ServerConnectionTypeProxy ... ServerConnectionTypeProxy ServerConnectionType = "Proxy" // ServerConnectionTypeRedirect ... ServerConnectionTypeRedirect ServerConnectionType = "Redirect" ) // PossibleServerConnectionTypeValues returns an array of possible values for the ServerConnectionType const type. func PossibleServerConnectionTypeValues() []ServerConnectionType { return []ServerConnectionType{ServerConnectionTypeDefault, ServerConnectionTypeProxy, ServerConnectionTypeRedirect} } // ServerKeyType enumerates the values for server key type. type ServerKeyType string const ( // AzureKeyVault ... AzureKeyVault ServerKeyType = "AzureKeyVault" // ServiceManaged ... ServiceManaged ServerKeyType = "ServiceManaged" ) // PossibleServerKeyTypeValues returns an array of possible values for the ServerKeyType const type. func PossibleServerKeyTypeValues() []ServerKeyType { return []ServerKeyType{AzureKeyVault, ServiceManaged} } // ServiceObjectiveName enumerates the values for service objective name. type ServiceObjectiveName string const ( // ServiceObjectiveNameBasic ... ServiceObjectiveNameBasic ServiceObjectiveName = "Basic" // ServiceObjectiveNameDS100 ... ServiceObjectiveNameDS100 ServiceObjectiveName = "DS100" // ServiceObjectiveNameDS1000 ... ServiceObjectiveNameDS1000 ServiceObjectiveName = "DS1000" // ServiceObjectiveNameDS1200 ... ServiceObjectiveNameDS1200 ServiceObjectiveName = "DS1200" // ServiceObjectiveNameDS1500 ... ServiceObjectiveNameDS1500 ServiceObjectiveName = "DS1500" // ServiceObjectiveNameDS200 ... ServiceObjectiveNameDS200 ServiceObjectiveName = "DS200" // ServiceObjectiveNameDS2000 ... ServiceObjectiveNameDS2000 ServiceObjectiveName = "DS2000" // ServiceObjectiveNameDS300 ... ServiceObjectiveNameDS300 ServiceObjectiveName = "DS300" // ServiceObjectiveNameDS400 ... ServiceObjectiveNameDS400 ServiceObjectiveName = "DS400" // ServiceObjectiveNameDS500 ... ServiceObjectiveNameDS500 ServiceObjectiveName = "DS500" // ServiceObjectiveNameDS600 ... ServiceObjectiveNameDS600 ServiceObjectiveName = "DS600" // ServiceObjectiveNameDW100 ... ServiceObjectiveNameDW100 ServiceObjectiveName = "DW100" // ServiceObjectiveNameDW1000 ... ServiceObjectiveNameDW1000 ServiceObjectiveName = "DW1000" // ServiceObjectiveNameDW10000c ... ServiceObjectiveNameDW10000c ServiceObjectiveName = "DW10000c" // ServiceObjectiveNameDW1000c ... ServiceObjectiveNameDW1000c ServiceObjectiveName = "DW1000c" // ServiceObjectiveNameDW1200 ... ServiceObjectiveNameDW1200 ServiceObjectiveName = "DW1200" // ServiceObjectiveNameDW1500 ... ServiceObjectiveNameDW1500 ServiceObjectiveName = "DW1500" // ServiceObjectiveNameDW15000c ... ServiceObjectiveNameDW15000c ServiceObjectiveName = "DW15000c" // ServiceObjectiveNameDW1500c ... ServiceObjectiveNameDW1500c ServiceObjectiveName = "DW1500c" // ServiceObjectiveNameDW200 ... ServiceObjectiveNameDW200 ServiceObjectiveName = "DW200" // ServiceObjectiveNameDW2000 ... ServiceObjectiveNameDW2000 ServiceObjectiveName = "DW2000" // ServiceObjectiveNameDW2000c ... ServiceObjectiveNameDW2000c ServiceObjectiveName = "DW2000c" // ServiceObjectiveNameDW2500c ... ServiceObjectiveNameDW2500c ServiceObjectiveName = "DW2500c" // ServiceObjectiveNameDW300 ... ServiceObjectiveNameDW300 ServiceObjectiveName = "DW300" // ServiceObjectiveNameDW3000 ... ServiceObjectiveNameDW3000 ServiceObjectiveName = "DW3000" // ServiceObjectiveNameDW30000c ... ServiceObjectiveNameDW30000c ServiceObjectiveName = "DW30000c" // ServiceObjectiveNameDW3000c ... ServiceObjectiveNameDW3000c ServiceObjectiveName = "DW3000c" // ServiceObjectiveNameDW400 ... ServiceObjectiveNameDW400 ServiceObjectiveName = "DW400" // ServiceObjectiveNameDW500 ... ServiceObjectiveNameDW500 ServiceObjectiveName = "DW500" // ServiceObjectiveNameDW5000c ... ServiceObjectiveNameDW5000c ServiceObjectiveName = "DW5000c" // ServiceObjectiveNameDW600 ... ServiceObjectiveNameDW600 ServiceObjectiveName = "DW600" // ServiceObjectiveNameDW6000 ... ServiceObjectiveNameDW6000 ServiceObjectiveName = "DW6000" // ServiceObjectiveNameDW6000c ... ServiceObjectiveNameDW6000c ServiceObjectiveName = "DW6000c" // ServiceObjectiveNameDW7500c ... ServiceObjectiveNameDW7500c ServiceObjectiveName = "DW7500c" // ServiceObjectiveNameElasticPool ... ServiceObjectiveNameElasticPool ServiceObjectiveName = "ElasticPool" // ServiceObjectiveNameFree ... ServiceObjectiveNameFree ServiceObjectiveName = "Free" // ServiceObjectiveNameP1 ... ServiceObjectiveNameP1 ServiceObjectiveName = "P1" // ServiceObjectiveNameP11 ... ServiceObjectiveNameP11 ServiceObjectiveName = "P11" // ServiceObjectiveNameP15 ... ServiceObjectiveNameP15 ServiceObjectiveName = "P15" // ServiceObjectiveNameP2 ... ServiceObjectiveNameP2 ServiceObjectiveName = "P2" // ServiceObjectiveNameP3 ... ServiceObjectiveNameP3 ServiceObjectiveName = "P3" // ServiceObjectiveNameP4 ... ServiceObjectiveNameP4 ServiceObjectiveName = "P4" // ServiceObjectiveNameP6 ... ServiceObjectiveNameP6 ServiceObjectiveName = "P6" // ServiceObjectiveNamePRS1 ... ServiceObjectiveNamePRS1 ServiceObjectiveName = "PRS1" // ServiceObjectiveNamePRS2 ... ServiceObjectiveNamePRS2 ServiceObjectiveName = "PRS2" // ServiceObjectiveNamePRS4 ... ServiceObjectiveNamePRS4 ServiceObjectiveName = "PRS4" // ServiceObjectiveNamePRS6 ... ServiceObjectiveNamePRS6 ServiceObjectiveName = "PRS6" // ServiceObjectiveNameS0 ... ServiceObjectiveNameS0 ServiceObjectiveName = "S0" // ServiceObjectiveNameS1 ... ServiceObjectiveNameS1 ServiceObjectiveName = "S1" // ServiceObjectiveNameS12 ... ServiceObjectiveNameS12 ServiceObjectiveName = "S12" // ServiceObjectiveNameS2 ... ServiceObjectiveNameS2 ServiceObjectiveName = "S2" // ServiceObjectiveNameS3 ... ServiceObjectiveNameS3 ServiceObjectiveName = "S3" // ServiceObjectiveNameS4 ... ServiceObjectiveNameS4 ServiceObjectiveName = "S4" // ServiceObjectiveNameS6 ... ServiceObjectiveNameS6 ServiceObjectiveName = "S6" // ServiceObjectiveNameS7 ... ServiceObjectiveNameS7 ServiceObjectiveName = "S7" // ServiceObjectiveNameS9 ... ServiceObjectiveNameS9 ServiceObjectiveName = "S9" // ServiceObjectiveNameSystem ... ServiceObjectiveNameSystem ServiceObjectiveName = "System" // ServiceObjectiveNameSystem0 ... ServiceObjectiveNameSystem0 ServiceObjectiveName = "System0" // ServiceObjectiveNameSystem1 ... ServiceObjectiveNameSystem1 ServiceObjectiveName = "System1" // ServiceObjectiveNameSystem2 ... ServiceObjectiveNameSystem2 ServiceObjectiveName = "System2" // ServiceObjectiveNameSystem2L ... ServiceObjectiveNameSystem2L ServiceObjectiveName = "System2L" // ServiceObjectiveNameSystem3 ... ServiceObjectiveNameSystem3 ServiceObjectiveName = "System3" // ServiceObjectiveNameSystem3L ... ServiceObjectiveNameSystem3L ServiceObjectiveName = "System3L" // ServiceObjectiveNameSystem4 ... ServiceObjectiveNameSystem4 ServiceObjectiveName = "System4" // ServiceObjectiveNameSystem4L ... ServiceObjectiveNameSystem4L ServiceObjectiveName = "System4L" ) // PossibleServiceObjectiveNameValues returns an array of possible values for the ServiceObjectiveName const type. func PossibleServiceObjectiveNameValues() []ServiceObjectiveName { return []ServiceObjectiveName{ServiceObjectiveNameBasic, ServiceObjectiveNameDS100, ServiceObjectiveNameDS1000, ServiceObjectiveNameDS1200, ServiceObjectiveNameDS1500, ServiceObjectiveNameDS200, ServiceObjectiveNameDS2000, ServiceObjectiveNameDS300, ServiceObjectiveNameDS400, ServiceObjectiveNameDS500, ServiceObjectiveNameDS600, ServiceObjectiveNameDW100, ServiceObjectiveNameDW1000, ServiceObjectiveNameDW10000c, ServiceObjectiveNameDW1000c, ServiceObjectiveNameDW1200, ServiceObjectiveNameDW1500, ServiceObjectiveNameDW15000c, ServiceObjectiveNameDW1500c, ServiceObjectiveNameDW200, ServiceObjectiveNameDW2000, ServiceObjectiveNameDW2000c, ServiceObjectiveNameDW2500c, ServiceObjectiveNameDW300, ServiceObjectiveNameDW3000, ServiceObjectiveNameDW30000c, ServiceObjectiveNameDW3000c, ServiceObjectiveNameDW400, ServiceObjectiveNameDW500, ServiceObjectiveNameDW5000c, ServiceObjectiveNameDW600, ServiceObjectiveNameDW6000, ServiceObjectiveNameDW6000c, ServiceObjectiveNameDW7500c, ServiceObjectiveNameElasticPool, ServiceObjectiveNameFree, ServiceObjectiveNameP1, ServiceObjectiveNameP11, ServiceObjectiveNameP15, ServiceObjectiveNameP2, ServiceObjectiveNameP3, ServiceObjectiveNameP4, ServiceObjectiveNameP6, ServiceObjectiveNamePRS1, ServiceObjectiveNamePRS2, ServiceObjectiveNamePRS4, ServiceObjectiveNamePRS6, ServiceObjectiveNameS0, ServiceObjectiveNameS1, ServiceObjectiveNameS12, ServiceObjectiveNameS2, ServiceObjectiveNameS3, ServiceObjectiveNameS4, ServiceObjectiveNameS6, ServiceObjectiveNameS7, ServiceObjectiveNameS9, ServiceObjectiveNameSystem, ServiceObjectiveNameSystem0, ServiceObjectiveNameSystem1, ServiceObjectiveNameSystem2, ServiceObjectiveNameSystem2L, ServiceObjectiveNameSystem3, ServiceObjectiveNameSystem3L, ServiceObjectiveNameSystem4, ServiceObjectiveNameSystem4L} } // StorageKeyType enumerates the values for storage key type. type StorageKeyType string const ( // SharedAccessKey ... SharedAccessKey StorageKeyType = "SharedAccessKey" // StorageAccessKey ... StorageAccessKey StorageKeyType = "StorageAccessKey" ) // PossibleStorageKeyTypeValues returns an array of possible values for the StorageKeyType const type. func PossibleStorageKeyTypeValues() []StorageKeyType { return []StorageKeyType{SharedAccessKey, StorageAccessKey} } // SyncAgentState enumerates the values for sync agent state. type SyncAgentState string const ( // SyncAgentStateNeverConnected ... SyncAgentStateNeverConnected SyncAgentState = "NeverConnected" // SyncAgentStateOffline ... SyncAgentStateOffline SyncAgentState = "Offline" // SyncAgentStateOnline ... SyncAgentStateOnline SyncAgentState = "Online" ) // PossibleSyncAgentStateValues returns an array of possible values for the SyncAgentState const type. func PossibleSyncAgentStateValues() []SyncAgentState { return []SyncAgentState{SyncAgentStateNeverConnected, SyncAgentStateOffline, SyncAgentStateOnline} } // SyncConflictResolutionPolicy enumerates the values for sync conflict resolution policy. type SyncConflictResolutionPolicy string const ( // HubWin ... HubWin SyncConflictResolutionPolicy = "HubWin" // MemberWin ... MemberWin SyncConflictResolutionPolicy = "MemberWin" ) // PossibleSyncConflictResolutionPolicyValues returns an array of possible values for the SyncConflictResolutionPolicy const type. func PossibleSyncConflictResolutionPolicyValues() []SyncConflictResolutionPolicy { return []SyncConflictResolutionPolicy{HubWin, MemberWin} } // SyncDirection enumerates the values for sync direction. type SyncDirection string const ( // Bidirectional ... Bidirectional SyncDirection = "Bidirectional" // OneWayHubToMember ... OneWayHubToMember SyncDirection = "OneWayHubToMember" // OneWayMemberToHub ... OneWayMemberToHub SyncDirection = "OneWayMemberToHub" ) // PossibleSyncDirectionValues returns an array of possible values for the SyncDirection const type. func PossibleSyncDirectionValues() []SyncDirection { return []SyncDirection{Bidirectional, OneWayHubToMember, OneWayMemberToHub} } // SyncGroupLogType enumerates the values for sync group log type. type SyncGroupLogType string const ( // SyncGroupLogTypeAll ... SyncGroupLogTypeAll SyncGroupLogType = "All" // SyncGroupLogTypeError ... SyncGroupLogTypeError SyncGroupLogType = "Error" // SyncGroupLogTypeSuccess ... SyncGroupLogTypeSuccess SyncGroupLogType = "Success" // SyncGroupLogTypeWarning ... SyncGroupLogTypeWarning SyncGroupLogType = "Warning" ) // PossibleSyncGroupLogTypeValues returns an array of possible values for the SyncGroupLogType const type. func PossibleSyncGroupLogTypeValues() []SyncGroupLogType { return []SyncGroupLogType{SyncGroupLogTypeAll, SyncGroupLogTypeError, SyncGroupLogTypeSuccess, SyncGroupLogTypeWarning} } // SyncGroupState enumerates the values for sync group state. type SyncGroupState string const ( // Error ... Error SyncGroupState = "Error" // Good ... Good SyncGroupState = "Good" // NotReady ... NotReady SyncGroupState = "NotReady" // Progressing ... Progressing SyncGroupState = "Progressing" // Warning ... Warning SyncGroupState = "Warning" ) // PossibleSyncGroupStateValues returns an array of possible values for the SyncGroupState const type. func PossibleSyncGroupStateValues() []SyncGroupState { return []SyncGroupState{Error, Good, NotReady, Progressing, Warning} } // SyncMemberDbType enumerates the values for sync member db type. type SyncMemberDbType string const ( // AzureSQLDatabase ... AzureSQLDatabase SyncMemberDbType = "AzureSqlDatabase" // SQLServerDatabase ... SQLServerDatabase SyncMemberDbType = "SqlServerDatabase" ) // PossibleSyncMemberDbTypeValues returns an array of possible values for the SyncMemberDbType const type. func PossibleSyncMemberDbTypeValues() []SyncMemberDbType { return []SyncMemberDbType{AzureSQLDatabase, SQLServerDatabase} } // SyncMemberState enumerates the values for sync member state. type SyncMemberState string const ( // DeProvisioned ... DeProvisioned SyncMemberState = "DeProvisioned" // DeProvisionFailed ... DeProvisionFailed SyncMemberState = "DeProvisionFailed" // DeProvisioning ... DeProvisioning SyncMemberState = "DeProvisioning" // DisabledBackupRestore ... DisabledBackupRestore SyncMemberState = "DisabledBackupRestore" // DisabledTombstoneCleanup ... DisabledTombstoneCleanup SyncMemberState = "DisabledTombstoneCleanup" // Provisioned ... Provisioned SyncMemberState = "Provisioned" // ProvisionFailed ... ProvisionFailed SyncMemberState = "ProvisionFailed" // Provisioning ... Provisioning SyncMemberState = "Provisioning" // ReprovisionFailed ... ReprovisionFailed SyncMemberState = "ReprovisionFailed" // Reprovisioning ... Reprovisioning SyncMemberState = "Reprovisioning" // SyncCancelled ... SyncCancelled SyncMemberState = "SyncCancelled" // SyncCancelling ... SyncCancelling SyncMemberState = "SyncCancelling" // SyncFailed ... SyncFailed SyncMemberState = "SyncFailed" // SyncInProgress ... SyncInProgress SyncMemberState = "SyncInProgress" // SyncSucceeded ... SyncSucceeded SyncMemberState = "SyncSucceeded" // SyncSucceededWithWarnings ... SyncSucceededWithWarnings SyncMemberState = "SyncSucceededWithWarnings" // UnProvisioned ... UnProvisioned SyncMemberState = "UnProvisioned" // UnReprovisioned ... UnReprovisioned SyncMemberState = "UnReprovisioned" ) // PossibleSyncMemberStateValues returns an array of possible values for the SyncMemberState const type. func PossibleSyncMemberStateValues() []SyncMemberState { return []SyncMemberState{DeProvisioned, DeProvisionFailed, DeProvisioning, DisabledBackupRestore, DisabledTombstoneCleanup, Provisioned, ProvisionFailed, Provisioning, ReprovisionFailed, Reprovisioning, SyncCancelled, SyncCancelling, SyncFailed, SyncInProgress, SyncSucceeded, SyncSucceededWithWarnings, UnProvisioned, UnReprovisioned} } // TransparentDataEncryptionActivityStatus enumerates the values for transparent data encryption activity // status. type TransparentDataEncryptionActivityStatus string const ( // Decrypting ... Decrypting TransparentDataEncryptionActivityStatus = "Decrypting" // Encrypting ... Encrypting TransparentDataEncryptionActivityStatus = "Encrypting" ) // PossibleTransparentDataEncryptionActivityStatusValues returns an array of possible values for the TransparentDataEncryptionActivityStatus const type. func PossibleTransparentDataEncryptionActivityStatusValues() []TransparentDataEncryptionActivityStatus { return []TransparentDataEncryptionActivityStatus{Decrypting, Encrypting} } // TransparentDataEncryptionStatus enumerates the values for transparent data encryption status. type TransparentDataEncryptionStatus string const ( // TransparentDataEncryptionStatusDisabled ... TransparentDataEncryptionStatusDisabled TransparentDataEncryptionStatus = "Disabled" // TransparentDataEncryptionStatusEnabled ... TransparentDataEncryptionStatusEnabled TransparentDataEncryptionStatus = "Enabled" ) // PossibleTransparentDataEncryptionStatusValues returns an array of possible values for the TransparentDataEncryptionStatus const type. func PossibleTransparentDataEncryptionStatusValues() []TransparentDataEncryptionStatus { return []TransparentDataEncryptionStatus{TransparentDataEncryptionStatusDisabled, TransparentDataEncryptionStatusEnabled} } // UnitDefinitionType enumerates the values for unit definition type. type UnitDefinitionType string const ( // UnitDefinitionTypeBytes ... UnitDefinitionTypeBytes UnitDefinitionType = "Bytes" // UnitDefinitionTypeBytesPerSecond ... UnitDefinitionTypeBytesPerSecond UnitDefinitionType = "BytesPerSecond" // UnitDefinitionTypeCount ... UnitDefinitionTypeCount UnitDefinitionType = "Count" // UnitDefinitionTypeCountPerSecond ... UnitDefinitionTypeCountPerSecond UnitDefinitionType = "CountPerSecond" // UnitDefinitionTypePercent ... UnitDefinitionTypePercent UnitDefinitionType = "Percent" // UnitDefinitionTypeSeconds ... UnitDefinitionTypeSeconds UnitDefinitionType = "Seconds" ) // PossibleUnitDefinitionTypeValues returns an array of possible values for the UnitDefinitionType const type. func PossibleUnitDefinitionTypeValues() []UnitDefinitionType { return []UnitDefinitionType{UnitDefinitionTypeBytes, UnitDefinitionTypeBytesPerSecond, UnitDefinitionTypeCount, UnitDefinitionTypeCountPerSecond, UnitDefinitionTypePercent, UnitDefinitionTypeSeconds} } // UnitType enumerates the values for unit type. type UnitType string const ( // UnitTypeBytes ... UnitTypeBytes UnitType = "bytes" // UnitTypeBytesPerSecond ... UnitTypeBytesPerSecond UnitType = "bytesPerSecond" // UnitTypeCount ... UnitTypeCount UnitType = "count" // UnitTypeCountPerSecond ... UnitTypeCountPerSecond UnitType = "countPerSecond" // UnitTypePercent ... UnitTypePercent UnitType = "percent" // UnitTypeSeconds ... UnitTypeSeconds UnitType = "seconds" ) // PossibleUnitTypeValues returns an array of possible values for the UnitType const type. func PossibleUnitTypeValues() []UnitType { return []UnitType{UnitTypeBytes, UnitTypeBytesPerSecond, UnitTypeCount, UnitTypeCountPerSecond, UnitTypePercent, UnitTypeSeconds} } // VirtualNetworkRuleState enumerates the values for virtual network rule state. type VirtualNetworkRuleState string const ( // VirtualNetworkRuleStateDeleting ... VirtualNetworkRuleStateDeleting VirtualNetworkRuleState = "Deleting" // VirtualNetworkRuleStateInitializing ... VirtualNetworkRuleStateInitializing VirtualNetworkRuleState = "Initializing" // VirtualNetworkRuleStateInProgress ... VirtualNetworkRuleStateInProgress VirtualNetworkRuleState = "InProgress" // VirtualNetworkRuleStateReady ... VirtualNetworkRuleStateReady VirtualNetworkRuleState = "Ready" // VirtualNetworkRuleStateUnknown ... VirtualNetworkRuleStateUnknown VirtualNetworkRuleState = "Unknown" ) // PossibleVirtualNetworkRuleStateValues returns an array of possible values for the VirtualNetworkRuleState const type. func PossibleVirtualNetworkRuleStateValues() []VirtualNetworkRuleState { return []VirtualNetworkRuleState{VirtualNetworkRuleStateDeleting, VirtualNetworkRuleStateInitializing, VirtualNetworkRuleStateInProgress, VirtualNetworkRuleStateReady, VirtualNetworkRuleStateUnknown} } // VulnerabilityAssessmentPolicyBaselineName enumerates the values for vulnerability assessment policy baseline // name. type VulnerabilityAssessmentPolicyBaselineName string const ( // VulnerabilityAssessmentPolicyBaselineNameDefault ... VulnerabilityAssessmentPolicyBaselineNameDefault VulnerabilityAssessmentPolicyBaselineName = "default" // VulnerabilityAssessmentPolicyBaselineNameMaster ... VulnerabilityAssessmentPolicyBaselineNameMaster VulnerabilityAssessmentPolicyBaselineName = "master" ) // PossibleVulnerabilityAssessmentPolicyBaselineNameValues returns an array of possible values for the VulnerabilityAssessmentPolicyBaselineName const type. func PossibleVulnerabilityAssessmentPolicyBaselineNameValues() []VulnerabilityAssessmentPolicyBaselineName { return []VulnerabilityAssessmentPolicyBaselineName{VulnerabilityAssessmentPolicyBaselineNameDefault, VulnerabilityAssessmentPolicyBaselineNameMaster} } // VulnerabilityAssessmentScanState enumerates the values for vulnerability assessment scan state. type VulnerabilityAssessmentScanState string const ( // VulnerabilityAssessmentScanStateFailed ... VulnerabilityAssessmentScanStateFailed VulnerabilityAssessmentScanState = "Failed" // VulnerabilityAssessmentScanStateFailedToRun ... VulnerabilityAssessmentScanStateFailedToRun VulnerabilityAssessmentScanState = "FailedToRun" // VulnerabilityAssessmentScanStateInProgress ... VulnerabilityAssessmentScanStateInProgress VulnerabilityAssessmentScanState = "InProgress" // VulnerabilityAssessmentScanStatePassed ... VulnerabilityAssessmentScanStatePassed VulnerabilityAssessmentScanState = "Passed" ) // PossibleVulnerabilityAssessmentScanStateValues returns an array of possible values for the VulnerabilityAssessmentScanState const type. func PossibleVulnerabilityAssessmentScanStateValues() []VulnerabilityAssessmentScanState { return []VulnerabilityAssessmentScanState{VulnerabilityAssessmentScanStateFailed, VulnerabilityAssessmentScanStateFailedToRun, VulnerabilityAssessmentScanStateInProgress, VulnerabilityAssessmentScanStatePassed} } // VulnerabilityAssessmentScanTriggerType enumerates the values for vulnerability assessment scan trigger type. type VulnerabilityAssessmentScanTriggerType string const ( // VulnerabilityAssessmentScanTriggerTypeOnDemand ... VulnerabilityAssessmentScanTriggerTypeOnDemand VulnerabilityAssessmentScanTriggerType = "OnDemand" // VulnerabilityAssessmentScanTriggerTypeRecurring ... VulnerabilityAssessmentScanTriggerTypeRecurring VulnerabilityAssessmentScanTriggerType = "Recurring" ) // PossibleVulnerabilityAssessmentScanTriggerTypeValues returns an array of possible values for the VulnerabilityAssessmentScanTriggerType const type. func PossibleVulnerabilityAssessmentScanTriggerTypeValues() []VulnerabilityAssessmentScanTriggerType { return []VulnerabilityAssessmentScanTriggerType{VulnerabilityAssessmentScanTriggerTypeOnDemand, VulnerabilityAssessmentScanTriggerTypeRecurring} } // AutomaticTuningOptions automatic tuning properties for individual advisors. type AutomaticTuningOptions struct { // DesiredState - Automatic tuning option desired state. Possible values include: 'AutomaticTuningOptionModeDesiredOff', 'AutomaticTuningOptionModeDesiredOn', 'AutomaticTuningOptionModeDesiredDefault' DesiredState AutomaticTuningOptionModeDesired `json:"desiredState,omitempty"` // ActualState - READ-ONLY; Automatic tuning option actual state. Possible values include: 'Off', 'On' ActualState AutomaticTuningOptionModeActual `json:"actualState,omitempty"` // ReasonCode - READ-ONLY; Reason code if desired and actual state are different. ReasonCode *int32 `json:"reasonCode,omitempty"` // ReasonDesc - READ-ONLY; Reason description if desired and actual state are different. Possible values include: 'Default', 'Disabled', 'AutoConfigured', 'InheritedFromServer', 'QueryStoreOff', 'QueryStoreReadOnly', 'NotSupported' ReasonDesc AutomaticTuningDisabledReason `json:"reasonDesc,omitempty"` } // AutomaticTuningServerOptions automatic tuning properties for individual advisors. type AutomaticTuningServerOptions struct { // DesiredState - Automatic tuning option desired state. Possible values include: 'AutomaticTuningOptionModeDesiredOff', 'AutomaticTuningOptionModeDesiredOn', 'AutomaticTuningOptionModeDesiredDefault' DesiredState AutomaticTuningOptionModeDesired `json:"desiredState,omitempty"` // ActualState - READ-ONLY; Automatic tuning option actual state. Possible values include: 'Off', 'On' ActualState AutomaticTuningOptionModeActual `json:"actualState,omitempty"` // ReasonCode - READ-ONLY; Reason code if desired and actual state are different. ReasonCode *int32 `json:"reasonCode,omitempty"` // ReasonDesc - READ-ONLY; Reason description if desired and actual state are different. Possible values include: 'AutomaticTuningServerReasonDefault', 'AutomaticTuningServerReasonDisabled', 'AutomaticTuningServerReasonAutoConfigured' ReasonDesc AutomaticTuningServerReason `json:"reasonDesc,omitempty"` } // AutomaticTuningServerProperties server-level Automatic Tuning properties. type AutomaticTuningServerProperties struct { // DesiredState - Automatic tuning desired state. Possible values include: 'AutomaticTuningServerModeCustom', 'AutomaticTuningServerModeAuto', 'AutomaticTuningServerModeUnspecified' DesiredState AutomaticTuningServerMode `json:"desiredState,omitempty"` // ActualState - READ-ONLY; Automatic tuning actual state. Possible values include: 'AutomaticTuningServerModeCustom', 'AutomaticTuningServerModeAuto', 'AutomaticTuningServerModeUnspecified' ActualState AutomaticTuningServerMode `json:"actualState,omitempty"` // Options - Automatic tuning options definition. Options map[string]*AutomaticTuningServerOptions `json:"options"` } // MarshalJSON is the custom marshaler for AutomaticTuningServerProperties. func (atsp AutomaticTuningServerProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if atsp.DesiredState != "" { objectMap["desiredState"] = atsp.DesiredState } if atsp.Options != nil { objectMap["options"] = atsp.Options } return json.Marshal(objectMap) } // BackupLongTermRetentionPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type BackupLongTermRetentionPoliciesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *BackupLongTermRetentionPoliciesCreateOrUpdateFuture) Result(client BackupLongTermRetentionPoliciesClient) (bltrp BackupLongTermRetentionPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.BackupLongTermRetentionPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.BackupLongTermRetentionPoliciesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if bltrp.Response.Response, err = future.GetResult(sender); err == nil && bltrp.Response.Response.StatusCode != http.StatusNoContent { bltrp, err = client.CreateOrUpdateResponder(bltrp.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.BackupLongTermRetentionPoliciesCreateOrUpdateFuture", "Result", bltrp.Response.Response, "Failure responding to request") } } return } // BackupLongTermRetentionPolicy a long term retention policy. type BackupLongTermRetentionPolicy struct { autorest.Response `json:"-"` // LongTermRetentionPolicyProperties - Resource properties. *LongTermRetentionPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for BackupLongTermRetentionPolicy. func (bltrp BackupLongTermRetentionPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if bltrp.LongTermRetentionPolicyProperties != nil { objectMap["properties"] = bltrp.LongTermRetentionPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for BackupLongTermRetentionPolicy struct. func (bltrp *BackupLongTermRetentionPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var longTermRetentionPolicyProperties LongTermRetentionPolicyProperties err = json.Unmarshal(*v, &longTermRetentionPolicyProperties) if err != nil { return err } bltrp.LongTermRetentionPolicyProperties = &longTermRetentionPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } bltrp.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } bltrp.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } bltrp.Type = &typeVar } } } return nil } // BackupShortTermRetentionPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type BackupShortTermRetentionPoliciesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *BackupShortTermRetentionPoliciesCreateOrUpdateFuture) Result(client BackupShortTermRetentionPoliciesClient) (bstrp BackupShortTermRetentionPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.BackupShortTermRetentionPoliciesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if bstrp.Response.Response, err = future.GetResult(sender); err == nil && bstrp.Response.Response.StatusCode != http.StatusNoContent { bstrp, err = client.CreateOrUpdateResponder(bstrp.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesCreateOrUpdateFuture", "Result", bstrp.Response.Response, "Failure responding to request") } } return } // BackupShortTermRetentionPoliciesUpdateFuture an abstraction for monitoring and retrieving the results of // a long-running operation. type BackupShortTermRetentionPoliciesUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *BackupShortTermRetentionPoliciesUpdateFuture) Result(client BackupShortTermRetentionPoliciesClient) (bstrp BackupShortTermRetentionPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.BackupShortTermRetentionPoliciesUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if bstrp.Response.Response, err = future.GetResult(sender); err == nil && bstrp.Response.Response.StatusCode != http.StatusNoContent { bstrp, err = client.UpdateResponder(bstrp.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.BackupShortTermRetentionPoliciesUpdateFuture", "Result", bstrp.Response.Response, "Failure responding to request") } } return } // BackupShortTermRetentionPolicy a short term retention policy. type BackupShortTermRetentionPolicy struct { autorest.Response `json:"-"` // BackupShortTermRetentionPolicyProperties - Resource properties. *BackupShortTermRetentionPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for BackupShortTermRetentionPolicy. func (bstrp BackupShortTermRetentionPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if bstrp.BackupShortTermRetentionPolicyProperties != nil { objectMap["properties"] = bstrp.BackupShortTermRetentionPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for BackupShortTermRetentionPolicy struct. func (bstrp *BackupShortTermRetentionPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var backupShortTermRetentionPolicyProperties BackupShortTermRetentionPolicyProperties err = json.Unmarshal(*v, &backupShortTermRetentionPolicyProperties) if err != nil { return err } bstrp.BackupShortTermRetentionPolicyProperties = &backupShortTermRetentionPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } bstrp.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } bstrp.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } bstrp.Type = &typeVar } } } return nil } // BackupShortTermRetentionPolicyListResult a list of short term retention policies. type BackupShortTermRetentionPolicyListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]BackupShortTermRetentionPolicy `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // BackupShortTermRetentionPolicyListResultIterator provides access to a complete listing of // BackupShortTermRetentionPolicy values. type BackupShortTermRetentionPolicyListResultIterator struct { i int page BackupShortTermRetentionPolicyListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *BackupShortTermRetentionPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/BackupShortTermRetentionPolicyListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *BackupShortTermRetentionPolicyListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter BackupShortTermRetentionPolicyListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter BackupShortTermRetentionPolicyListResultIterator) Response() BackupShortTermRetentionPolicyListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter BackupShortTermRetentionPolicyListResultIterator) Value() BackupShortTermRetentionPolicy { if !iter.page.NotDone() { return BackupShortTermRetentionPolicy{} } return iter.page.Values()[iter.i] } // Creates a new instance of the BackupShortTermRetentionPolicyListResultIterator type. func NewBackupShortTermRetentionPolicyListResultIterator(page BackupShortTermRetentionPolicyListResultPage) BackupShortTermRetentionPolicyListResultIterator { return BackupShortTermRetentionPolicyListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (bstrplr BackupShortTermRetentionPolicyListResult) IsEmpty() bool { return bstrplr.Value == nil || len(*bstrplr.Value) == 0 } // backupShortTermRetentionPolicyListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (bstrplr BackupShortTermRetentionPolicyListResult) backupShortTermRetentionPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { if bstrplr.NextLink == nil || len(to.String(bstrplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(bstrplr.NextLink))) } // BackupShortTermRetentionPolicyListResultPage contains a page of BackupShortTermRetentionPolicy values. type BackupShortTermRetentionPolicyListResultPage struct { fn func(context.Context, BackupShortTermRetentionPolicyListResult) (BackupShortTermRetentionPolicyListResult, error) bstrplr BackupShortTermRetentionPolicyListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *BackupShortTermRetentionPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/BackupShortTermRetentionPolicyListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.bstrplr) if err != nil { return err } page.bstrplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *BackupShortTermRetentionPolicyListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page BackupShortTermRetentionPolicyListResultPage) NotDone() bool { return !page.bstrplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page BackupShortTermRetentionPolicyListResultPage) Response() BackupShortTermRetentionPolicyListResult { return page.bstrplr } // Values returns the slice of values for the current page or nil if there are no values. func (page BackupShortTermRetentionPolicyListResultPage) Values() []BackupShortTermRetentionPolicy { if page.bstrplr.IsEmpty() { return nil } return *page.bstrplr.Value } // Creates a new instance of the BackupShortTermRetentionPolicyListResultPage type. func NewBackupShortTermRetentionPolicyListResultPage(getNextPage func(context.Context, BackupShortTermRetentionPolicyListResult) (BackupShortTermRetentionPolicyListResult, error)) BackupShortTermRetentionPolicyListResultPage { return BackupShortTermRetentionPolicyListResultPage{fn: getNextPage} } // BackupShortTermRetentionPolicyProperties properties of a short term retention policy type BackupShortTermRetentionPolicyProperties struct { // RetentionDays - The backup retention period in days. This is how many days Point-in-Time Restore will be supported. RetentionDays *int32 `json:"retentionDays,omitempty"` } // CheckNameAvailabilityRequest a request to check whether the specified name for a resource is available. type CheckNameAvailabilityRequest struct { // Name - The name whose availability is to be checked. Name *string `json:"name,omitempty"` // Type - The type of resource that is used as the scope of the availability check. Type *string `json:"type,omitempty"` } // CheckNameAvailabilityResponse a response indicating whether the specified name for a resource is // available. type CheckNameAvailabilityResponse struct { autorest.Response `json:"-"` // Available - READ-ONLY; True if the name is available, otherwise false. Available *bool `json:"available,omitempty"` // Message - READ-ONLY; A message explaining why the name is unavailable. Will be null if the name is available. Message *string `json:"message,omitempty"` // Name - READ-ONLY; The name whose availability was checked. Name *string `json:"name,omitempty"` // Reason - READ-ONLY; The reason code explaining why the name is unavailable. Will be null if the name is available. Possible values include: 'Invalid', 'AlreadyExists' Reason CheckNameAvailabilityReason `json:"reason,omitempty"` } // CompleteDatabaseRestoreDefinition contains the information necessary to perform a complete database // restore operation. type CompleteDatabaseRestoreDefinition struct { // LastBackupName - The last backup name to apply LastBackupName *string `json:"lastBackupName,omitempty"` } // CreateDatabaseRestorePointDefinition contains the information necessary to perform a create database // restore point operation. type CreateDatabaseRestorePointDefinition struct { // RestorePointLabel - The restore point label to apply RestorePointLabel *string `json:"restorePointLabel,omitempty"` } // Database a database resource. type Database struct { autorest.Response `json:"-"` // Sku - The database SKU. // // The list of SKUs may vary by region and support offer. To determine the SKUs (including the SKU name, tier/edition, family, and capacity) that are available to your subscription in an Azure region, use the `Capabilities_ListByLocation` REST API or one of the following commands: // // ```azurecli // az sql db list-editions -l <location> -o table // ```` // // ```powershell // Get-AzSqlServerServiceObjective -Location <location> // ```` Sku *Sku `json:"sku,omitempty"` // Kind - READ-ONLY; Kind of database. This is metadata used for the Azure portal experience. Kind *string `json:"kind,omitempty"` // ManagedBy - READ-ONLY; Resource that manages the database. ManagedBy *string `json:"managedBy,omitempty"` // DatabaseProperties - Resource properties. *DatabaseProperties `json:"properties,omitempty"` // Location - Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for Database. func (d Database) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if d.Sku != nil { objectMap["sku"] = d.Sku } if d.DatabaseProperties != nil { objectMap["properties"] = d.DatabaseProperties } if d.Location != nil { objectMap["location"] = d.Location } if d.Tags != nil { objectMap["tags"] = d.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for Database struct. func (d *Database) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "sku": if v != nil { var sku Sku err = json.Unmarshal(*v, &sku) if err != nil { return err } d.Sku = &sku } case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } d.Kind = &kind } case "managedBy": if v != nil { var managedBy string err = json.Unmarshal(*v, &managedBy) if err != nil { return err } d.ManagedBy = &managedBy } case "properties": if v != nil { var databaseProperties DatabaseProperties err = json.Unmarshal(*v, &databaseProperties) if err != nil { return err } d.DatabaseProperties = &databaseProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } d.Location = &location } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } d.Tags = tags } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } d.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } d.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } d.Type = &typeVar } } } return nil } // DatabaseAutomaticTuning database-level Automatic Tuning. type DatabaseAutomaticTuning struct { autorest.Response `json:"-"` // DatabaseAutomaticTuningProperties - Resource properties. *DatabaseAutomaticTuningProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for DatabaseAutomaticTuning. func (dat DatabaseAutomaticTuning) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if dat.DatabaseAutomaticTuningProperties != nil { objectMap["properties"] = dat.DatabaseAutomaticTuningProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for DatabaseAutomaticTuning struct. func (dat *DatabaseAutomaticTuning) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var databaseAutomaticTuningProperties DatabaseAutomaticTuningProperties err = json.Unmarshal(*v, &databaseAutomaticTuningProperties) if err != nil { return err } dat.DatabaseAutomaticTuningProperties = &databaseAutomaticTuningProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } dat.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } dat.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } dat.Type = &typeVar } } } return nil } // DatabaseAutomaticTuningProperties database-level Automatic Tuning properties. type DatabaseAutomaticTuningProperties struct { // DesiredState - Automatic tuning desired state. Possible values include: 'Inherit', 'Custom', 'Auto', 'Unspecified' DesiredState AutomaticTuningMode `json:"desiredState,omitempty"` // ActualState - READ-ONLY; Automatic tuning actual state. Possible values include: 'Inherit', 'Custom', 'Auto', 'Unspecified' ActualState AutomaticTuningMode `json:"actualState,omitempty"` // Options - Automatic tuning options definition. Options map[string]*AutomaticTuningOptions `json:"options"` } // MarshalJSON is the custom marshaler for DatabaseAutomaticTuningProperties. func (datp DatabaseAutomaticTuningProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if datp.DesiredState != "" { objectMap["desiredState"] = datp.DesiredState } if datp.Options != nil { objectMap["options"] = datp.Options } return json.Marshal(objectMap) } // DatabaseBlobAuditingPolicy a database blob auditing policy. type DatabaseBlobAuditingPolicy struct { autorest.Response `json:"-"` // Kind - READ-ONLY; Resource kind. Kind *string `json:"kind,omitempty"` // DatabaseBlobAuditingPolicyProperties - Resource properties. *DatabaseBlobAuditingPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for DatabaseBlobAuditingPolicy. func (dbap DatabaseBlobAuditingPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if dbap.DatabaseBlobAuditingPolicyProperties != nil { objectMap["properties"] = dbap.DatabaseBlobAuditingPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for DatabaseBlobAuditingPolicy struct. func (dbap *DatabaseBlobAuditingPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } dbap.Kind = &kind } case "properties": if v != nil { var databaseBlobAuditingPolicyProperties DatabaseBlobAuditingPolicyProperties err = json.Unmarshal(*v, &databaseBlobAuditingPolicyProperties) if err != nil { return err } dbap.DatabaseBlobAuditingPolicyProperties = &databaseBlobAuditingPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } dbap.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } dbap.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } dbap.Type = &typeVar } } } return nil } // DatabaseBlobAuditingPolicyListResult a list of database auditing settings. type DatabaseBlobAuditingPolicyListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]DatabaseBlobAuditingPolicy `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // DatabaseBlobAuditingPolicyListResultIterator provides access to a complete listing of // DatabaseBlobAuditingPolicy values. type DatabaseBlobAuditingPolicyListResultIterator struct { i int page DatabaseBlobAuditingPolicyListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *DatabaseBlobAuditingPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseBlobAuditingPolicyListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *DatabaseBlobAuditingPolicyListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter DatabaseBlobAuditingPolicyListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter DatabaseBlobAuditingPolicyListResultIterator) Response() DatabaseBlobAuditingPolicyListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter DatabaseBlobAuditingPolicyListResultIterator) Value() DatabaseBlobAuditingPolicy { if !iter.page.NotDone() { return DatabaseBlobAuditingPolicy{} } return iter.page.Values()[iter.i] } // Creates a new instance of the DatabaseBlobAuditingPolicyListResultIterator type. func NewDatabaseBlobAuditingPolicyListResultIterator(page DatabaseBlobAuditingPolicyListResultPage) DatabaseBlobAuditingPolicyListResultIterator { return DatabaseBlobAuditingPolicyListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (dbaplr DatabaseBlobAuditingPolicyListResult) IsEmpty() bool { return dbaplr.Value == nil || len(*dbaplr.Value) == 0 } // databaseBlobAuditingPolicyListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (dbaplr DatabaseBlobAuditingPolicyListResult) databaseBlobAuditingPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { if dbaplr.NextLink == nil || len(to.String(dbaplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(dbaplr.NextLink))) } // DatabaseBlobAuditingPolicyListResultPage contains a page of DatabaseBlobAuditingPolicy values. type DatabaseBlobAuditingPolicyListResultPage struct { fn func(context.Context, DatabaseBlobAuditingPolicyListResult) (DatabaseBlobAuditingPolicyListResult, error) dbaplr DatabaseBlobAuditingPolicyListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *DatabaseBlobAuditingPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseBlobAuditingPolicyListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.dbaplr) if err != nil { return err } page.dbaplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *DatabaseBlobAuditingPolicyListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page DatabaseBlobAuditingPolicyListResultPage) NotDone() bool { return !page.dbaplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page DatabaseBlobAuditingPolicyListResultPage) Response() DatabaseBlobAuditingPolicyListResult { return page.dbaplr } // Values returns the slice of values for the current page or nil if there are no values. func (page DatabaseBlobAuditingPolicyListResultPage) Values() []DatabaseBlobAuditingPolicy { if page.dbaplr.IsEmpty() { return nil } return *page.dbaplr.Value } // Creates a new instance of the DatabaseBlobAuditingPolicyListResultPage type. func NewDatabaseBlobAuditingPolicyListResultPage(getNextPage func(context.Context, DatabaseBlobAuditingPolicyListResult) (DatabaseBlobAuditingPolicyListResult, error)) DatabaseBlobAuditingPolicyListResultPage { return DatabaseBlobAuditingPolicyListResultPage{fn: getNextPage} } // DatabaseBlobAuditingPolicyProperties properties of a database blob auditing policy. type DatabaseBlobAuditingPolicyProperties struct { // State - Specifies the state of the policy. If state is Enabled, storageEndpoint or isAzureMonitorTargetEnabled are required. Possible values include: 'BlobAuditingPolicyStateEnabled', 'BlobAuditingPolicyStateDisabled' State BlobAuditingPolicyState `json:"state,omitempty"` // StorageEndpoint - Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). If state is Enabled, storageEndpoint is required. StorageEndpoint *string `json:"storageEndpoint,omitempty"` // StorageAccountAccessKey - Specifies the identifier key of the auditing storage account. If state is Enabled and storageEndpoint is specified, storageAccountAccessKey is required. StorageAccountAccessKey *string `json:"storageAccountAccessKey,omitempty"` // RetentionDays - Specifies the number of days to keep in the audit logs in the storage account. RetentionDays *int32 `json:"retentionDays,omitempty"` // AuditActionsAndGroups - Specifies the Actions-Groups and Actions to audit. // // The recommended set of action groups to use is the following combination - this will audit all the queries and stored procedures executed against the database, as well as successful and failed logins: // // BATCH_COMPLETED_GROUP, // SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP, // FAILED_DATABASE_AUTHENTICATION_GROUP. // // This above combination is also the set that is configured by default when enabling auditing from the Azure portal. // // The supported action groups to audit are (note: choose only specific groups that cover your auditing needs. Using unnecessary groups could lead to very large quantities of audit records): // // APPLICATION_ROLE_CHANGE_PASSWORD_GROUP // BACKUP_RESTORE_GROUP // DATABASE_LOGOUT_GROUP // DATABASE_OBJECT_CHANGE_GROUP // DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP // DATABASE_OBJECT_PERMISSION_CHANGE_GROUP // DATABASE_OPERATION_GROUP // DATABASE_PERMISSION_CHANGE_GROUP // DATABASE_PRINCIPAL_CHANGE_GROUP // DATABASE_PRINCIPAL_IMPERSONATION_GROUP // DATABASE_ROLE_MEMBER_CHANGE_GROUP // FAILED_DATABASE_AUTHENTICATION_GROUP // SCHEMA_OBJECT_ACCESS_GROUP // SCHEMA_OBJECT_CHANGE_GROUP // SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP // SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP // SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP // USER_CHANGE_PASSWORD_GROUP // BATCH_STARTED_GROUP // BATCH_COMPLETED_GROUP // // These are groups that cover all sql statements and stored procedures executed against the database, and should not be used in combination with other groups as this will result in duplicate audit logs. // // For more information, see [Database-Level Audit Action Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups). // // For Database auditing policy, specific Actions can also be specified (note that Actions cannot be specified for Server auditing policy). The supported actions to audit are: // SELECT // UPDATE // INSERT // DELETE // EXECUTE // RECEIVE // REFERENCES // // The general form for defining an action to be audited is: // {action} ON {object} BY {principal} // // Note that <object> in the above format can refer to an object like a table, view, or stored procedure, or an entire database or schema. For the latter cases, the forms DATABASE::{db_name} and SCHEMA::{schema_name} are used, respectively. // // For example: // SELECT on dbo.myTable by public // SELECT on DATABASE::myDatabase by public // SELECT on SCHEMA::mySchema by public // // For more information, see [Database-Level Audit Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions) AuditActionsAndGroups *[]string `json:"auditActionsAndGroups,omitempty"` // StorageAccountSubscriptionID - Specifies the blob storage subscription Id. StorageAccountSubscriptionID *uuid.UUID `json:"storageAccountSubscriptionId,omitempty"` // IsStorageSecondaryKeyInUse - Specifies whether storageAccountAccessKey value is the storage's secondary key. IsStorageSecondaryKeyInUse *bool `json:"isStorageSecondaryKeyInUse,omitempty"` // IsAzureMonitorTargetEnabled - Specifies whether audit events are sent to Azure Monitor. // In order to send the events to Azure Monitor, specify 'state' as 'Enabled' and 'isAzureMonitorTargetEnabled' as true. // // When using REST API to configure auditing, Diagnostic Settings with 'SQLSecurityAuditEvents' diagnostic logs category on the database should be also created. // Note that for server level audit you should use the 'master' database as {databaseName}. // // Diagnostic Settings URI format: // PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview // // For more information, see [Diagnostic Settings REST API](https://go.microsoft.com/fwlink/?linkid=2033207) // or [Diagnostic Settings PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043) IsAzureMonitorTargetEnabled *bool `json:"isAzureMonitorTargetEnabled,omitempty"` } // DatabaseListResult a list of databases. type DatabaseListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]Database `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // DatabaseListResultIterator provides access to a complete listing of Database values. type DatabaseListResultIterator struct { i int page DatabaseListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *DatabaseListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *DatabaseListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter DatabaseListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter DatabaseListResultIterator) Response() DatabaseListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter DatabaseListResultIterator) Value() Database { if !iter.page.NotDone() { return Database{} } return iter.page.Values()[iter.i] } // Creates a new instance of the DatabaseListResultIterator type. func NewDatabaseListResultIterator(page DatabaseListResultPage) DatabaseListResultIterator { return DatabaseListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (dlr DatabaseListResult) IsEmpty() bool { return dlr.Value == nil || len(*dlr.Value) == 0 } // databaseListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (dlr DatabaseListResult) databaseListResultPreparer(ctx context.Context) (*http.Request, error) { if dlr.NextLink == nil || len(to.String(dlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(dlr.NextLink))) } // DatabaseListResultPage contains a page of Database values. type DatabaseListResultPage struct { fn func(context.Context, DatabaseListResult) (DatabaseListResult, error) dlr DatabaseListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *DatabaseListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.dlr) if err != nil { return err } page.dlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *DatabaseListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page DatabaseListResultPage) NotDone() bool { return !page.dlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page DatabaseListResultPage) Response() DatabaseListResult { return page.dlr } // Values returns the slice of values for the current page or nil if there are no values. func (page DatabaseListResultPage) Values() []Database { if page.dlr.IsEmpty() { return nil } return *page.dlr.Value } // Creates a new instance of the DatabaseListResultPage type. func NewDatabaseListResultPage(getNextPage func(context.Context, DatabaseListResult) (DatabaseListResult, error)) DatabaseListResultPage { return DatabaseListResultPage{fn: getNextPage} } // DatabaseOperation a database operation. type DatabaseOperation struct { // DatabaseOperationProperties - Resource properties. *DatabaseOperationProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for DatabaseOperation. func (do DatabaseOperation) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if do.DatabaseOperationProperties != nil { objectMap["properties"] = do.DatabaseOperationProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for DatabaseOperation struct. func (do *DatabaseOperation) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var databaseOperationProperties DatabaseOperationProperties err = json.Unmarshal(*v, &databaseOperationProperties) if err != nil { return err } do.DatabaseOperationProperties = &databaseOperationProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } do.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } do.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } do.Type = &typeVar } } } return nil } // DatabaseOperationListResult the response to a list database operations request type DatabaseOperationListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]DatabaseOperation `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // DatabaseOperationListResultIterator provides access to a complete listing of DatabaseOperation values. type DatabaseOperationListResultIterator struct { i int page DatabaseOperationListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *DatabaseOperationListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseOperationListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *DatabaseOperationListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter DatabaseOperationListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter DatabaseOperationListResultIterator) Response() DatabaseOperationListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter DatabaseOperationListResultIterator) Value() DatabaseOperation { if !iter.page.NotDone() { return DatabaseOperation{} } return iter.page.Values()[iter.i] } // Creates a new instance of the DatabaseOperationListResultIterator type. func NewDatabaseOperationListResultIterator(page DatabaseOperationListResultPage) DatabaseOperationListResultIterator { return DatabaseOperationListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (dolr DatabaseOperationListResult) IsEmpty() bool { return dolr.Value == nil || len(*dolr.Value) == 0 } // databaseOperationListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (dolr DatabaseOperationListResult) databaseOperationListResultPreparer(ctx context.Context) (*http.Request, error) { if dolr.NextLink == nil || len(to.String(dolr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(dolr.NextLink))) } // DatabaseOperationListResultPage contains a page of DatabaseOperation values. type DatabaseOperationListResultPage struct { fn func(context.Context, DatabaseOperationListResult) (DatabaseOperationListResult, error) dolr DatabaseOperationListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *DatabaseOperationListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseOperationListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.dolr) if err != nil { return err } page.dolr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *DatabaseOperationListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page DatabaseOperationListResultPage) NotDone() bool { return !page.dolr.IsEmpty() } // Response returns the raw server response from the last page request. func (page DatabaseOperationListResultPage) Response() DatabaseOperationListResult { return page.dolr } // Values returns the slice of values for the current page or nil if there are no values. func (page DatabaseOperationListResultPage) Values() []DatabaseOperation { if page.dolr.IsEmpty() { return nil } return *page.dolr.Value } // Creates a new instance of the DatabaseOperationListResultPage type. func NewDatabaseOperationListResultPage(getNextPage func(context.Context, DatabaseOperationListResult) (DatabaseOperationListResult, error)) DatabaseOperationListResultPage { return DatabaseOperationListResultPage{fn: getNextPage} } // DatabaseOperationProperties the properties of a database operation. type DatabaseOperationProperties struct { // DatabaseName - READ-ONLY; The name of the database the operation is being performed on. DatabaseName *string `json:"databaseName,omitempty"` // Operation - READ-ONLY; The name of operation. Operation *string `json:"operation,omitempty"` // OperationFriendlyName - READ-ONLY; The friendly name of operation. OperationFriendlyName *string `json:"operationFriendlyName,omitempty"` // PercentComplete - READ-ONLY; The percentage of the operation completed. PercentComplete *int32 `json:"percentComplete,omitempty"` // ServerName - READ-ONLY; The name of the server. ServerName *string `json:"serverName,omitempty"` // StartTime - READ-ONLY; The operation start time. StartTime *date.Time `json:"startTime,omitempty"` // State - READ-ONLY; The operation state. Possible values include: 'ManagementOperationStatePending', 'ManagementOperationStateInProgress', 'ManagementOperationStateSucceeded', 'ManagementOperationStateFailed', 'ManagementOperationStateCancelInProgress', 'ManagementOperationStateCancelled' State ManagementOperationState `json:"state,omitempty"` // ErrorCode - READ-ONLY; The operation error code. ErrorCode *int32 `json:"errorCode,omitempty"` // ErrorDescription - READ-ONLY; The operation error description. ErrorDescription *string `json:"errorDescription,omitempty"` // ErrorSeverity - READ-ONLY; The operation error severity. ErrorSeverity *int32 `json:"errorSeverity,omitempty"` // IsUserError - READ-ONLY; Whether or not the error is a user error. IsUserError *bool `json:"isUserError,omitempty"` // EstimatedCompletionTime - READ-ONLY; The estimated completion time of the operation. EstimatedCompletionTime *date.Time `json:"estimatedCompletionTime,omitempty"` // Description - READ-ONLY; The operation description. Description *string `json:"description,omitempty"` // IsCancellable - READ-ONLY; Whether the operation can be cancelled. IsCancellable *bool `json:"isCancellable,omitempty"` } // DatabaseProperties the database's properties. type DatabaseProperties struct { // CreateMode - Specifies the mode of database creation. // // Default: regular database creation. // // Copy: creates a database as a copy of an existing database. sourceDatabaseId must be specified as the resource ID of the source database. // // Secondary: creates a database as a secondary replica of an existing database. sourceDatabaseId must be specified as the resource ID of the existing primary database. // // PointInTimeRestore: Creates a database by restoring a point in time backup of an existing database. sourceDatabaseId must be specified as the resource ID of the existing database, and restorePointInTime must be specified. // // Recovery: Creates a database by restoring a geo-replicated backup. sourceDatabaseId must be specified as the recoverable database resource ID to restore. // // Restore: Creates a database by restoring a backup of a deleted database. sourceDatabaseId must be specified. If sourceDatabaseId is the database's original resource ID, then sourceDatabaseDeletionDate must be specified. Otherwise sourceDatabaseId must be the restorable dropped database resource ID and sourceDatabaseDeletionDate is ignored. restorePointInTime may also be specified to restore from an earlier point in time. // // RestoreLongTermRetentionBackup: Creates a database by restoring from a long term retention vault. recoveryServicesRecoveryPointResourceId must be specified as the recovery point resource ID. // // Copy, Secondary, and RestoreLongTermRetentionBackup are not supported for DataWarehouse edition. Possible values include: 'CreateModeDefault', 'CreateModeCopy', 'CreateModeSecondary', 'CreateModePointInTimeRestore', 'CreateModeRestore', 'CreateModeRecovery', 'CreateModeRestoreExternalBackup', 'CreateModeRestoreExternalBackupSecondary', 'CreateModeRestoreLongTermRetentionBackup', 'CreateModeOnlineSecondary' CreateMode CreateMode `json:"createMode,omitempty"` // Collation - The collation of the database. Collation *string `json:"collation,omitempty"` // MaxSizeBytes - The max size of the database expressed in bytes. MaxSizeBytes *int64 `json:"maxSizeBytes,omitempty"` // SampleName - The name of the sample schema to apply when creating this database. Possible values include: 'AdventureWorksLT', 'WideWorldImportersStd', 'WideWorldImportersFull' SampleName SampleName `json:"sampleName,omitempty"` // ElasticPoolID - The resource identifier of the elastic pool containing this database. ElasticPoolID *string `json:"elasticPoolId,omitempty"` // SourceDatabaseID - The resource identifier of the source database associated with create operation of this database. SourceDatabaseID *string `json:"sourceDatabaseId,omitempty"` // Status - READ-ONLY; The status of the database. Possible values include: 'DatabaseStatusOnline', 'DatabaseStatusRestoring', 'DatabaseStatusRecoveryPending', 'DatabaseStatusRecovering', 'DatabaseStatusSuspect', 'DatabaseStatusOffline', 'DatabaseStatusStandby', 'DatabaseStatusShutdown', 'DatabaseStatusEmergencyMode', 'DatabaseStatusAutoClosed', 'DatabaseStatusCopying', 'DatabaseStatusCreating', 'DatabaseStatusInaccessible', 'DatabaseStatusOfflineSecondary', 'DatabaseStatusPausing', 'DatabaseStatusPaused', 'DatabaseStatusResuming', 'DatabaseStatusScaling', 'DatabaseStatusOfflineChangingDwPerformanceTiers', 'DatabaseStatusOnlineChangingDwPerformanceTiers', 'DatabaseStatusDisabled' Status DatabaseStatus `json:"status,omitempty"` // DatabaseID - READ-ONLY; The ID of the database. DatabaseID *uuid.UUID `json:"databaseId,omitempty"` // CreationDate - READ-ONLY; The creation date of the database (ISO8601 format). CreationDate *date.Time `json:"creationDate,omitempty"` // CurrentServiceObjectiveName - READ-ONLY; The current service level objective name of the database. CurrentServiceObjectiveName *string `json:"currentServiceObjectiveName,omitempty"` // RequestedServiceObjectiveName - READ-ONLY; The requested service level objective name of the database. RequestedServiceObjectiveName *string `json:"requestedServiceObjectiveName,omitempty"` // DefaultSecondaryLocation - READ-ONLY; The default secondary region for this database. DefaultSecondaryLocation *string `json:"defaultSecondaryLocation,omitempty"` // FailoverGroupID - READ-ONLY; Failover Group resource identifier that this database belongs to. FailoverGroupID *string `json:"failoverGroupId,omitempty"` // RestorePointInTime - Specifies the point in time (ISO8601 format) of the source database that will be restored to create the new database. RestorePointInTime *date.Time `json:"restorePointInTime,omitempty"` // SourceDatabaseDeletionDate - Specifies the time that the database was deleted. SourceDatabaseDeletionDate *date.Time `json:"sourceDatabaseDeletionDate,omitempty"` // RecoveryServicesRecoveryPointID - The resource identifier of the recovery point associated with create operation of this database. RecoveryServicesRecoveryPointID *string `json:"recoveryServicesRecoveryPointId,omitempty"` // LongTermRetentionBackupResourceID - The resource identifier of the long term retention backup associated with create operation of this database. LongTermRetentionBackupResourceID *string `json:"longTermRetentionBackupResourceId,omitempty"` // RecoverableDatabaseID - The resource identifier of the recoverable database associated with create operation of this database. RecoverableDatabaseID *string `json:"recoverableDatabaseId,omitempty"` // RestorableDroppedDatabaseID - The resource identifier of the restorable dropped database associated with create operation of this database. RestorableDroppedDatabaseID *string `json:"restorableDroppedDatabaseId,omitempty"` // CatalogCollation - Collation of the metadata catalog. Possible values include: 'DATABASEDEFAULT', 'SQLLatin1GeneralCP1CIAS' CatalogCollation CatalogCollationType `json:"catalogCollation,omitempty"` // ZoneRedundant - Whether or not this database is zone redundant, which means the replicas of this database will be spread across multiple availability zones. ZoneRedundant *bool `json:"zoneRedundant,omitempty"` // LicenseType - The license type to apply for this database. Possible values include: 'LicenseIncluded', 'BasePrice' LicenseType DatabaseLicenseType `json:"licenseType,omitempty"` // MaxLogSizeBytes - READ-ONLY; The max log size for this database. MaxLogSizeBytes *int64 `json:"maxLogSizeBytes,omitempty"` // EarliestRestoreDate - READ-ONLY; This records the earliest start date and time that restore is available for this database (ISO8601 format). EarliestRestoreDate *date.Time `json:"earliestRestoreDate,omitempty"` // ReadScale - If enabled, connections that have application intent set to readonly in their connection string may be routed to a readonly secondary replica. This property is only settable for Premium and Business Critical databases. Possible values include: 'DatabaseReadScaleEnabled', 'DatabaseReadScaleDisabled' ReadScale DatabaseReadScale `json:"readScale,omitempty"` // ReadReplicaCount - The number of readonly secondary replicas associated with the database to which readonly application intent connections may be routed. This property is only settable for Hyperscale edition databases. ReadReplicaCount *int32 `json:"readReplicaCount,omitempty"` // CurrentSku - READ-ONLY; The name and tier of the SKU. CurrentSku *Sku `json:"currentSku,omitempty"` // AutoPauseDelay - Time in minutes after which database is automatically paused. A value of -1 means that automatic pause is disabled AutoPauseDelay *int32 `json:"autoPauseDelay,omitempty"` // MinCapacity - Minimal capacity that database will always have allocated, if not paused MinCapacity *float64 `json:"minCapacity,omitempty"` // PausedDate - READ-ONLY; The date when database was paused by user configuration or action (ISO8601 format). Null if the database is ready. PausedDate *date.Time `json:"pausedDate,omitempty"` // ResumedDate - READ-ONLY; The date when database was resumed by user action or database login (ISO8601 format). Null if the database is paused. ResumedDate *date.Time `json:"resumedDate,omitempty"` } // DatabasesCreateImportOperationFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type DatabasesCreateImportOperationFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabasesCreateImportOperationFuture) Result(client DatabasesClient) (ier ImportExportResponse, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesCreateImportOperationFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabasesCreateImportOperationFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ier.Response.Response, err = future.GetResult(sender); err == nil && ier.Response.Response.StatusCode != http.StatusNoContent { ier, err = client.CreateImportOperationResponder(ier.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesCreateImportOperationFuture", "Result", ier.Response.Response, "Failure responding to request") } } return } // DatabasesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type DatabasesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabasesCreateOrUpdateFuture) Result(client DatabasesClient) (d Database, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabasesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { d, err = client.CreateOrUpdateResponder(d.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesCreateOrUpdateFuture", "Result", d.Response.Response, "Failure responding to request") } } return } // DatabasesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type DatabasesDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabasesDeleteFuture) Result(client DatabasesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabasesDeleteFuture") return } ar.Response = future.Response() return } // DatabaseSecurityAlertPolicy contains information about a database Threat Detection policy. type DatabaseSecurityAlertPolicy struct { autorest.Response `json:"-"` // Location - The geo-location where the resource lives Location *string `json:"location,omitempty"` // Kind - READ-ONLY; Resource kind. Kind *string `json:"kind,omitempty"` // DatabaseSecurityAlertPolicyProperties - Properties of the security alert policy. *DatabaseSecurityAlertPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for DatabaseSecurityAlertPolicy. func (dsap DatabaseSecurityAlertPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if dsap.Location != nil { objectMap["location"] = dsap.Location } if dsap.DatabaseSecurityAlertPolicyProperties != nil { objectMap["properties"] = dsap.DatabaseSecurityAlertPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for DatabaseSecurityAlertPolicy struct. func (dsap *DatabaseSecurityAlertPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } dsap.Location = &location } case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } dsap.Kind = &kind } case "properties": if v != nil { var databaseSecurityAlertPolicyProperties DatabaseSecurityAlertPolicyProperties err = json.Unmarshal(*v, &databaseSecurityAlertPolicyProperties) if err != nil { return err } dsap.DatabaseSecurityAlertPolicyProperties = &databaseSecurityAlertPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } dsap.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } dsap.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } dsap.Type = &typeVar } } } return nil } // DatabaseSecurityAlertPolicyProperties properties for a database Threat Detection policy. type DatabaseSecurityAlertPolicyProperties struct { // State - Specifies the state of the policy. If state is Enabled, storageEndpoint and storageAccountAccessKey are required. Possible values include: 'SecurityAlertPolicyStateNew', 'SecurityAlertPolicyStateEnabled', 'SecurityAlertPolicyStateDisabled' State SecurityAlertPolicyState `json:"state,omitempty"` // DisabledAlerts - Specifies the semicolon-separated list of alerts that are disabled, or empty string to disable no alerts. Possible values: Sql_Injection; Sql_Injection_Vulnerability; Access_Anomaly; Data_Exfiltration; Unsafe_Action. DisabledAlerts *string `json:"disabledAlerts,omitempty"` // EmailAddresses - Specifies the semicolon-separated list of e-mail addresses to which the alert is sent. EmailAddresses *string `json:"emailAddresses,omitempty"` // EmailAccountAdmins - Specifies that the alert is sent to the account administrators. Possible values include: 'SecurityAlertPolicyEmailAccountAdminsEnabled', 'SecurityAlertPolicyEmailAccountAdminsDisabled' EmailAccountAdmins SecurityAlertPolicyEmailAccountAdmins `json:"emailAccountAdmins,omitempty"` // StorageEndpoint - Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection audit logs. If state is Enabled, storageEndpoint is required. StorageEndpoint *string `json:"storageEndpoint,omitempty"` // StorageAccountAccessKey - Specifies the identifier key of the Threat Detection audit storage account. If state is Enabled, storageAccountAccessKey is required. StorageAccountAccessKey *string `json:"storageAccountAccessKey,omitempty"` // RetentionDays - Specifies the number of days to keep in the Threat Detection audit logs. RetentionDays *int32 `json:"retentionDays,omitempty"` // UseServerDefault - Specifies whether to use the default server policy. Possible values include: 'SecurityAlertPolicyUseServerDefaultEnabled', 'SecurityAlertPolicyUseServerDefaultDisabled' UseServerDefault SecurityAlertPolicyUseServerDefault `json:"useServerDefault,omitempty"` } // DatabasesExportFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type DatabasesExportFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabasesExportFuture) Result(client DatabasesClient) (ier ImportExportResponse, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesExportFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabasesExportFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ier.Response.Response, err = future.GetResult(sender); err == nil && ier.Response.Response.StatusCode != http.StatusNoContent { ier, err = client.ExportResponder(ier.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesExportFuture", "Result", ier.Response.Response, "Failure responding to request") } } return } // DatabasesFailoverFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type DatabasesFailoverFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabasesFailoverFuture) Result(client DatabasesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesFailoverFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabasesFailoverFuture") return } ar.Response = future.Response() return } // DatabasesImportFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type DatabasesImportFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabasesImportFuture) Result(client DatabasesClient) (ier ImportExportResponse, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesImportFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabasesImportFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ier.Response.Response, err = future.GetResult(sender); err == nil && ier.Response.Response.StatusCode != http.StatusNoContent { ier, err = client.ImportResponder(ier.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesImportFuture", "Result", ier.Response.Response, "Failure responding to request") } } return } // DatabasesPauseFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type DatabasesPauseFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabasesPauseFuture) Result(client DatabasesClient) (d Database, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesPauseFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabasesPauseFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { d, err = client.PauseResponder(d.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesPauseFuture", "Result", d.Response.Response, "Failure responding to request") } } return } // DatabasesResumeFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type DatabasesResumeFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabasesResumeFuture) Result(client DatabasesClient) (d Database, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesResumeFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabasesResumeFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { d, err = client.ResumeResponder(d.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesResumeFuture", "Result", d.Response.Response, "Failure responding to request") } } return } // DatabasesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type DatabasesUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabasesUpdateFuture) Result(client DatabasesClient) (d Database, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabasesUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if d.Response.Response, err = future.GetResult(sender); err == nil && d.Response.Response.StatusCode != http.StatusNoContent { d, err = client.UpdateResponder(d.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesUpdateFuture", "Result", d.Response.Response, "Failure responding to request") } } return } // DatabasesUpgradeDataWarehouseFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type DatabasesUpgradeDataWarehouseFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabasesUpgradeDataWarehouseFuture) Result(client DatabasesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabasesUpgradeDataWarehouseFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabasesUpgradeDataWarehouseFuture") return } ar.Response = future.Response() return } // DatabaseUpdate a database resource. type DatabaseUpdate struct { // Sku - The name and tier of the SKU. Sku *Sku `json:"sku,omitempty"` // DatabaseProperties - Resource properties. *DatabaseProperties `json:"properties,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` } // MarshalJSON is the custom marshaler for DatabaseUpdate. func (du DatabaseUpdate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if du.Sku != nil { objectMap["sku"] = du.Sku } if du.DatabaseProperties != nil { objectMap["properties"] = du.DatabaseProperties } if du.Tags != nil { objectMap["tags"] = du.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for DatabaseUpdate struct. func (du *DatabaseUpdate) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "sku": if v != nil { var sku Sku err = json.Unmarshal(*v, &sku) if err != nil { return err } du.Sku = &sku } case "properties": if v != nil { var databaseProperties DatabaseProperties err = json.Unmarshal(*v, &databaseProperties) if err != nil { return err } du.DatabaseProperties = &databaseProperties } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } du.Tags = tags } } } return nil } // DatabaseUsage the database usages. type DatabaseUsage struct { // Name - READ-ONLY; The name of the usage metric. Name *string `json:"name,omitempty"` // ResourceName - READ-ONLY; The name of the resource. ResourceName *string `json:"resourceName,omitempty"` // DisplayName - READ-ONLY; The usage metric display name. DisplayName *string `json:"displayName,omitempty"` // CurrentValue - READ-ONLY; The current value of the usage metric. CurrentValue *float64 `json:"currentValue,omitempty"` // Limit - READ-ONLY; The current limit of the usage metric. Limit *float64 `json:"limit,omitempty"` // Unit - READ-ONLY; The units of the usage metric. Unit *string `json:"unit,omitempty"` // NextResetTime - READ-ONLY; The next reset time for the usage metric (ISO8601 format). NextResetTime *date.Time `json:"nextResetTime,omitempty"` } // DatabaseUsageListResult the response to a list database metrics request. type DatabaseUsageListResult struct { autorest.Response `json:"-"` // Value - The list of database usages for the database. Value *[]DatabaseUsage `json:"value,omitempty"` } // DatabaseVulnerabilityAssessment a database vulnerability assessment. type DatabaseVulnerabilityAssessment struct { autorest.Response `json:"-"` // DatabaseVulnerabilityAssessmentProperties - Resource properties. *DatabaseVulnerabilityAssessmentProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for DatabaseVulnerabilityAssessment. func (dva DatabaseVulnerabilityAssessment) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if dva.DatabaseVulnerabilityAssessmentProperties != nil { objectMap["properties"] = dva.DatabaseVulnerabilityAssessmentProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for DatabaseVulnerabilityAssessment struct. func (dva *DatabaseVulnerabilityAssessment) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var databaseVulnerabilityAssessmentProperties DatabaseVulnerabilityAssessmentProperties err = json.Unmarshal(*v, &databaseVulnerabilityAssessmentProperties) if err != nil { return err } dva.DatabaseVulnerabilityAssessmentProperties = &databaseVulnerabilityAssessmentProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } dva.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } dva.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } dva.Type = &typeVar } } } return nil } // DatabaseVulnerabilityAssessmentListResult a list of the database's vulnerability assessments. type DatabaseVulnerabilityAssessmentListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]DatabaseVulnerabilityAssessment `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // DatabaseVulnerabilityAssessmentListResultIterator provides access to a complete listing of // DatabaseVulnerabilityAssessment values. type DatabaseVulnerabilityAssessmentListResultIterator struct { i int page DatabaseVulnerabilityAssessmentListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *DatabaseVulnerabilityAssessmentListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseVulnerabilityAssessmentListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *DatabaseVulnerabilityAssessmentListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter DatabaseVulnerabilityAssessmentListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter DatabaseVulnerabilityAssessmentListResultIterator) Response() DatabaseVulnerabilityAssessmentListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter DatabaseVulnerabilityAssessmentListResultIterator) Value() DatabaseVulnerabilityAssessment { if !iter.page.NotDone() { return DatabaseVulnerabilityAssessment{} } return iter.page.Values()[iter.i] } // Creates a new instance of the DatabaseVulnerabilityAssessmentListResultIterator type. func NewDatabaseVulnerabilityAssessmentListResultIterator(page DatabaseVulnerabilityAssessmentListResultPage) DatabaseVulnerabilityAssessmentListResultIterator { return DatabaseVulnerabilityAssessmentListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (dvalr DatabaseVulnerabilityAssessmentListResult) IsEmpty() bool { return dvalr.Value == nil || len(*dvalr.Value) == 0 } // databaseVulnerabilityAssessmentListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (dvalr DatabaseVulnerabilityAssessmentListResult) databaseVulnerabilityAssessmentListResultPreparer(ctx context.Context) (*http.Request, error) { if dvalr.NextLink == nil || len(to.String(dvalr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(dvalr.NextLink))) } // DatabaseVulnerabilityAssessmentListResultPage contains a page of DatabaseVulnerabilityAssessment values. type DatabaseVulnerabilityAssessmentListResultPage struct { fn func(context.Context, DatabaseVulnerabilityAssessmentListResult) (DatabaseVulnerabilityAssessmentListResult, error) dvalr DatabaseVulnerabilityAssessmentListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *DatabaseVulnerabilityAssessmentListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DatabaseVulnerabilityAssessmentListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.dvalr) if err != nil { return err } page.dvalr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *DatabaseVulnerabilityAssessmentListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page DatabaseVulnerabilityAssessmentListResultPage) NotDone() bool { return !page.dvalr.IsEmpty() } // Response returns the raw server response from the last page request. func (page DatabaseVulnerabilityAssessmentListResultPage) Response() DatabaseVulnerabilityAssessmentListResult { return page.dvalr } // Values returns the slice of values for the current page or nil if there are no values. func (page DatabaseVulnerabilityAssessmentListResultPage) Values() []DatabaseVulnerabilityAssessment { if page.dvalr.IsEmpty() { return nil } return *page.dvalr.Value } // Creates a new instance of the DatabaseVulnerabilityAssessmentListResultPage type. func NewDatabaseVulnerabilityAssessmentListResultPage(getNextPage func(context.Context, DatabaseVulnerabilityAssessmentListResult) (DatabaseVulnerabilityAssessmentListResult, error)) DatabaseVulnerabilityAssessmentListResultPage { return DatabaseVulnerabilityAssessmentListResultPage{fn: getNextPage} } // DatabaseVulnerabilityAssessmentProperties properties of a database Vulnerability Assessment. type DatabaseVulnerabilityAssessmentProperties struct { // StorageContainerPath - A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/). It is required if server level vulnerability assessment policy doesn't set StorageContainerPath *string `json:"storageContainerPath,omitempty"` // StorageContainerSasKey - A shared access signature (SAS Key) that has write access to the blob container specified in 'storageContainerPath' parameter. If 'storageAccountAccessKey' isn't specified, StorageContainerSasKey is required. StorageContainerSasKey *string `json:"storageContainerSasKey,omitempty"` // StorageAccountAccessKey - Specifies the identifier key of the storage account for vulnerability assessment scan results. If 'StorageContainerSasKey' isn't specified, storageAccountAccessKey is required. StorageAccountAccessKey *string `json:"storageAccountAccessKey,omitempty"` // RecurringScans - The recurring scans settings RecurringScans *VulnerabilityAssessmentRecurringScansProperties `json:"recurringScans,omitempty"` } // DatabaseVulnerabilityAssessmentRuleBaseline a database vulnerability assessment rule baseline. type DatabaseVulnerabilityAssessmentRuleBaseline struct { autorest.Response `json:"-"` // DatabaseVulnerabilityAssessmentRuleBaselineProperties - Resource properties. *DatabaseVulnerabilityAssessmentRuleBaselineProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for DatabaseVulnerabilityAssessmentRuleBaseline. func (dvarb DatabaseVulnerabilityAssessmentRuleBaseline) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if dvarb.DatabaseVulnerabilityAssessmentRuleBaselineProperties != nil { objectMap["properties"] = dvarb.DatabaseVulnerabilityAssessmentRuleBaselineProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for DatabaseVulnerabilityAssessmentRuleBaseline struct. func (dvarb *DatabaseVulnerabilityAssessmentRuleBaseline) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var databaseVulnerabilityAssessmentRuleBaselineProperties DatabaseVulnerabilityAssessmentRuleBaselineProperties err = json.Unmarshal(*v, &databaseVulnerabilityAssessmentRuleBaselineProperties) if err != nil { return err } dvarb.DatabaseVulnerabilityAssessmentRuleBaselineProperties = &databaseVulnerabilityAssessmentRuleBaselineProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } dvarb.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } dvarb.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } dvarb.Type = &typeVar } } } return nil } // DatabaseVulnerabilityAssessmentRuleBaselineItem properties for an Azure SQL Database Vulnerability // Assessment rule baseline's result. type DatabaseVulnerabilityAssessmentRuleBaselineItem struct { // Result - The rule baseline result Result *[]string `json:"result,omitempty"` } // DatabaseVulnerabilityAssessmentRuleBaselineProperties properties of a database Vulnerability Assessment // rule baseline. type DatabaseVulnerabilityAssessmentRuleBaselineProperties struct { // BaselineResults - The rule baseline result BaselineResults *[]DatabaseVulnerabilityAssessmentRuleBaselineItem `json:"baselineResults,omitempty"` } // DatabaseVulnerabilityAssessmentScanExportProperties properties of the export operation's result. type DatabaseVulnerabilityAssessmentScanExportProperties struct { // ExportedReportLocation - READ-ONLY; Location of the exported report (e.g. https://myStorage.blob.core.windows.net/VaScans/scans/serverName/databaseName/scan_scanId.xlsx). ExportedReportLocation *string `json:"exportedReportLocation,omitempty"` } // DatabaseVulnerabilityAssessmentScansExport a database Vulnerability Assessment scan export resource. type DatabaseVulnerabilityAssessmentScansExport struct { autorest.Response `json:"-"` // DatabaseVulnerabilityAssessmentScanExportProperties - Resource properties. *DatabaseVulnerabilityAssessmentScanExportProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for DatabaseVulnerabilityAssessmentScansExport. func (dvase DatabaseVulnerabilityAssessmentScansExport) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if dvase.DatabaseVulnerabilityAssessmentScanExportProperties != nil { objectMap["properties"] = dvase.DatabaseVulnerabilityAssessmentScanExportProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for DatabaseVulnerabilityAssessmentScansExport struct. func (dvase *DatabaseVulnerabilityAssessmentScansExport) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var databaseVulnerabilityAssessmentScanExportProperties DatabaseVulnerabilityAssessmentScanExportProperties err = json.Unmarshal(*v, &databaseVulnerabilityAssessmentScanExportProperties) if err != nil { return err } dvase.DatabaseVulnerabilityAssessmentScanExportProperties = &databaseVulnerabilityAssessmentScanExportProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } dvase.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } dvase.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } dvase.Type = &typeVar } } } return nil } // DatabaseVulnerabilityAssessmentScansInitiateScanFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type DatabaseVulnerabilityAssessmentScansInitiateScanFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *DatabaseVulnerabilityAssessmentScansInitiateScanFuture) Result(client DatabaseVulnerabilityAssessmentScansClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.DatabaseVulnerabilityAssessmentScansInitiateScanFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.DatabaseVulnerabilityAssessmentScansInitiateScanFuture") return } ar.Response = future.Response() return } // DataMaskingPolicy represents a database data masking policy. type DataMaskingPolicy struct { autorest.Response `json:"-"` // DataMaskingPolicyProperties - The properties of the data masking policy. *DataMaskingPolicyProperties `json:"properties,omitempty"` // Location - READ-ONLY; The location of the data masking policy. Location *string `json:"location,omitempty"` // Kind - READ-ONLY; The kind of data masking policy. Metadata, used for Azure portal. Kind *string `json:"kind,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for DataMaskingPolicy. func (dmp DataMaskingPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if dmp.DataMaskingPolicyProperties != nil { objectMap["properties"] = dmp.DataMaskingPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for DataMaskingPolicy struct. func (dmp *DataMaskingPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var dataMaskingPolicyProperties DataMaskingPolicyProperties err = json.Unmarshal(*v, &dataMaskingPolicyProperties) if err != nil { return err } dmp.DataMaskingPolicyProperties = &dataMaskingPolicyProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } dmp.Location = &location } case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } dmp.Kind = &kind } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } dmp.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } dmp.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } dmp.Type = &typeVar } } } return nil } // DataMaskingPolicyProperties the properties of a database data masking policy. type DataMaskingPolicyProperties struct { // DataMaskingState - The state of the data masking policy. Possible values include: 'DataMaskingStateDisabled', 'DataMaskingStateEnabled' DataMaskingState DataMaskingState `json:"dataMaskingState,omitempty"` // ExemptPrincipals - The list of the exempt principals. Specifies the semicolon-separated list of database users for which the data masking policy does not apply. The specified users receive data results without masking for all of the database queries. ExemptPrincipals *string `json:"exemptPrincipals,omitempty"` // ApplicationPrincipals - READ-ONLY; The list of the application principals. This is a legacy parameter and is no longer used. ApplicationPrincipals *string `json:"applicationPrincipals,omitempty"` // MaskingLevel - READ-ONLY; The masking level. This is a legacy parameter and is no longer used. MaskingLevel *string `json:"maskingLevel,omitempty"` } // DataMaskingRule represents a database data masking rule. type DataMaskingRule struct { autorest.Response `json:"-"` // DataMaskingRuleProperties - The properties of the resource. *DataMaskingRuleProperties `json:"properties,omitempty"` // Location - READ-ONLY; The location of the data masking rule. Location *string `json:"location,omitempty"` // Kind - READ-ONLY; The kind of Data Masking Rule. Metadata, used for Azure portal. Kind *string `json:"kind,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for DataMaskingRule. func (dmr DataMaskingRule) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if dmr.DataMaskingRuleProperties != nil { objectMap["properties"] = dmr.DataMaskingRuleProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for DataMaskingRule struct. func (dmr *DataMaskingRule) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var dataMaskingRuleProperties DataMaskingRuleProperties err = json.Unmarshal(*v, &dataMaskingRuleProperties) if err != nil { return err } dmr.DataMaskingRuleProperties = &dataMaskingRuleProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } dmr.Location = &location } case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } dmr.Kind = &kind } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } dmr.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } dmr.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } dmr.Type = &typeVar } } } return nil } // DataMaskingRuleListResult the response to a list data masking rules request. type DataMaskingRuleListResult struct { autorest.Response `json:"-"` // Value - The list of database data masking rules. Value *[]DataMaskingRule `json:"value,omitempty"` } // DataMaskingRuleProperties the properties of a database data masking rule. type DataMaskingRuleProperties struct { // ID - READ-ONLY; The rule Id. ID *string `json:"id,omitempty"` // AliasName - The alias name. This is a legacy parameter and is no longer used. AliasName *string `json:"aliasName,omitempty"` // RuleState - The rule state. Used to delete a rule. To delete an existing rule, specify the schemaName, tableName, columnName, maskingFunction, and specify ruleState as disabled. However, if the rule doesn't already exist, the rule will be created with ruleState set to enabled, regardless of the provided value of ruleState. Possible values include: 'DataMaskingRuleStateDisabled', 'DataMaskingRuleStateEnabled' RuleState DataMaskingRuleState `json:"ruleState,omitempty"` // SchemaName - The schema name on which the data masking rule is applied. SchemaName *string `json:"schemaName,omitempty"` // TableName - The table name on which the data masking rule is applied. TableName *string `json:"tableName,omitempty"` // ColumnName - The column name on which the data masking rule is applied. ColumnName *string `json:"columnName,omitempty"` // MaskingFunction - The masking function that is used for the data masking rule. Possible values include: 'DataMaskingFunctionDefault', 'DataMaskingFunctionCCN', 'DataMaskingFunctionEmail', 'DataMaskingFunctionNumber', 'DataMaskingFunctionSSN', 'DataMaskingFunctionText' MaskingFunction DataMaskingFunction `json:"maskingFunction,omitempty"` // NumberFrom - The numberFrom property of the masking rule. Required if maskingFunction is set to Number, otherwise this parameter will be ignored. NumberFrom *string `json:"numberFrom,omitempty"` // NumberTo - The numberTo property of the data masking rule. Required if maskingFunction is set to Number, otherwise this parameter will be ignored. NumberTo *string `json:"numberTo,omitempty"` // PrefixSize - If maskingFunction is set to Text, the number of characters to show unmasked in the beginning of the string. Otherwise, this parameter will be ignored. PrefixSize *string `json:"prefixSize,omitempty"` // SuffixSize - If maskingFunction is set to Text, the number of characters to show unmasked at the end of the string. Otherwise, this parameter will be ignored. SuffixSize *string `json:"suffixSize,omitempty"` // ReplacementString - If maskingFunction is set to Text, the character to use for masking the unexposed part of the string. Otherwise, this parameter will be ignored. ReplacementString *string `json:"replacementString,omitempty"` } // EditionCapability the edition capability. type EditionCapability struct { // Name - READ-ONLY; The database edition name. Name *string `json:"name,omitempty"` // SupportedServiceLevelObjectives - READ-ONLY; The list of supported service objectives for the edition. SupportedServiceLevelObjectives *[]ServiceObjectiveCapability `json:"supportedServiceLevelObjectives,omitempty"` // ZoneRedundant - READ-ONLY; Whether or not zone redundancy is supported for the edition. ZoneRedundant *bool `json:"zoneRedundant,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ElasticPool an elastic pool. type ElasticPool struct { autorest.Response `json:"-"` // Sku - The elastic pool SKU. // // The list of SKUs may vary by region and support offer. To determine the SKUs (including the SKU name, tier/edition, family, and capacity) that are available to your subscription in an Azure region, use the `Capabilities_ListByLocation` REST API or the following command: // // ```azurecli // az sql elastic-pool list-editions -l <location> -o table // ```` Sku *Sku `json:"sku,omitempty"` // Kind - READ-ONLY; Kind of elastic pool. This is metadata used for the Azure portal experience. Kind *string `json:"kind,omitempty"` // ElasticPoolProperties - Resource properties. *ElasticPoolProperties `json:"properties,omitempty"` // Location - Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ElasticPool. func (ep ElasticPool) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if ep.Sku != nil { objectMap["sku"] = ep.Sku } if ep.ElasticPoolProperties != nil { objectMap["properties"] = ep.ElasticPoolProperties } if ep.Location != nil { objectMap["location"] = ep.Location } if ep.Tags != nil { objectMap["tags"] = ep.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ElasticPool struct. func (ep *ElasticPool) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "sku": if v != nil { var sku Sku err = json.Unmarshal(*v, &sku) if err != nil { return err } ep.Sku = &sku } case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } ep.Kind = &kind } case "properties": if v != nil { var elasticPoolProperties ElasticPoolProperties err = json.Unmarshal(*v, &elasticPoolProperties) if err != nil { return err } ep.ElasticPoolProperties = &elasticPoolProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } ep.Location = &location } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } ep.Tags = tags } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } ep.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } ep.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } ep.Type = &typeVar } } } return nil } // ElasticPoolActivity represents the activity on an elastic pool. type ElasticPoolActivity struct { // Location - The geo-location where the resource lives Location *string `json:"location,omitempty"` // ElasticPoolActivityProperties - The properties representing the resource. *ElasticPoolActivityProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ElasticPoolActivity. func (epa ElasticPoolActivity) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if epa.Location != nil { objectMap["location"] = epa.Location } if epa.ElasticPoolActivityProperties != nil { objectMap["properties"] = epa.ElasticPoolActivityProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ElasticPoolActivity struct. func (epa *ElasticPoolActivity) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } epa.Location = &location } case "properties": if v != nil { var elasticPoolActivityProperties ElasticPoolActivityProperties err = json.Unmarshal(*v, &elasticPoolActivityProperties) if err != nil { return err } epa.ElasticPoolActivityProperties = &elasticPoolActivityProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } epa.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } epa.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } epa.Type = &typeVar } } } return nil } // ElasticPoolActivityListResult represents the response to a list elastic pool activity request. type ElasticPoolActivityListResult struct { autorest.Response `json:"-"` // Value - The list of elastic pool activities. Value *[]ElasticPoolActivity `json:"value,omitempty"` } // ElasticPoolActivityProperties represents the properties of an elastic pool. type ElasticPoolActivityProperties struct { // EndTime - READ-ONLY; The time the operation finished (ISO8601 format). EndTime *date.Time `json:"endTime,omitempty"` // ErrorCode - READ-ONLY; The error code if available. ErrorCode *int32 `json:"errorCode,omitempty"` // ErrorMessage - READ-ONLY; The error message if available. ErrorMessage *string `json:"errorMessage,omitempty"` // ErrorSeverity - READ-ONLY; The error severity if available. ErrorSeverity *int32 `json:"errorSeverity,omitempty"` // Operation - READ-ONLY; The operation name. Operation *string `json:"operation,omitempty"` // OperationID - READ-ONLY; The unique operation ID. OperationID *uuid.UUID `json:"operationId,omitempty"` // PercentComplete - READ-ONLY; The percentage complete if available. PercentComplete *int32 `json:"percentComplete,omitempty"` // RequestedDatabaseDtuMax - READ-ONLY; The requested max DTU per database if available. RequestedDatabaseDtuMax *int32 `json:"requestedDatabaseDtuMax,omitempty"` // RequestedDatabaseDtuMin - READ-ONLY; The requested min DTU per database if available. RequestedDatabaseDtuMin *int32 `json:"requestedDatabaseDtuMin,omitempty"` // RequestedDtu - READ-ONLY; The requested DTU for the pool if available. RequestedDtu *int32 `json:"requestedDtu,omitempty"` // RequestedElasticPoolName - READ-ONLY; The requested name for the elastic pool if available. RequestedElasticPoolName *string `json:"requestedElasticPoolName,omitempty"` // RequestedStorageLimitInGB - READ-ONLY; The requested storage limit for the pool in GB if available. RequestedStorageLimitInGB *int64 `json:"requestedStorageLimitInGB,omitempty"` // ElasticPoolName - READ-ONLY; The name of the elastic pool. ElasticPoolName *string `json:"elasticPoolName,omitempty"` // ServerName - READ-ONLY; The name of the server the elastic pool is in. ServerName *string `json:"serverName,omitempty"` // StartTime - READ-ONLY; The time the operation started (ISO8601 format). StartTime *date.Time `json:"startTime,omitempty"` // State - READ-ONLY; The current state of the operation. State *string `json:"state,omitempty"` // RequestedStorageLimitInMB - READ-ONLY; The requested storage limit in MB. RequestedStorageLimitInMB *int32 `json:"requestedStorageLimitInMB,omitempty"` // RequestedDatabaseDtuGuarantee - READ-ONLY; The requested per database DTU guarantee. RequestedDatabaseDtuGuarantee *int32 `json:"requestedDatabaseDtuGuarantee,omitempty"` // RequestedDatabaseDtuCap - READ-ONLY; The requested per database DTU cap. RequestedDatabaseDtuCap *int32 `json:"requestedDatabaseDtuCap,omitempty"` // RequestedDtuGuarantee - READ-ONLY; The requested DTU guarantee. RequestedDtuGuarantee *int32 `json:"requestedDtuGuarantee,omitempty"` } // ElasticPoolDatabaseActivity represents the activity on an elastic pool. type ElasticPoolDatabaseActivity struct { // Location - The geo-location where the resource lives Location *string `json:"location,omitempty"` // ElasticPoolDatabaseActivityProperties - The properties representing the resource. *ElasticPoolDatabaseActivityProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ElasticPoolDatabaseActivity. func (epda ElasticPoolDatabaseActivity) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if epda.Location != nil { objectMap["location"] = epda.Location } if epda.ElasticPoolDatabaseActivityProperties != nil { objectMap["properties"] = epda.ElasticPoolDatabaseActivityProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ElasticPoolDatabaseActivity struct. func (epda *ElasticPoolDatabaseActivity) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } epda.Location = &location } case "properties": if v != nil { var elasticPoolDatabaseActivityProperties ElasticPoolDatabaseActivityProperties err = json.Unmarshal(*v, &elasticPoolDatabaseActivityProperties) if err != nil { return err } epda.ElasticPoolDatabaseActivityProperties = &elasticPoolDatabaseActivityProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } epda.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } epda.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } epda.Type = &typeVar } } } return nil } // ElasticPoolDatabaseActivityListResult represents the response to a list elastic pool database activity // request. type ElasticPoolDatabaseActivityListResult struct { autorest.Response `json:"-"` // Value - The list of elastic pool database activities. Value *[]ElasticPoolDatabaseActivity `json:"value,omitempty"` } // ElasticPoolDatabaseActivityProperties represents the properties of an elastic pool database activity. type ElasticPoolDatabaseActivityProperties struct { // DatabaseName - READ-ONLY; The database name. DatabaseName *string `json:"databaseName,omitempty"` // EndTime - READ-ONLY; The time the operation finished (ISO8601 format). EndTime *date.Time `json:"endTime,omitempty"` // ErrorCode - READ-ONLY; The error code if available. ErrorCode *int32 `json:"errorCode,omitempty"` // ErrorMessage - READ-ONLY; The error message if available. ErrorMessage *string `json:"errorMessage,omitempty"` // ErrorSeverity - READ-ONLY; The error severity if available. ErrorSeverity *int32 `json:"errorSeverity,omitempty"` // Operation - READ-ONLY; The operation name. Operation *string `json:"operation,omitempty"` // OperationID - READ-ONLY; The unique operation ID. OperationID *uuid.UUID `json:"operationId,omitempty"` // PercentComplete - READ-ONLY; The percentage complete if available. PercentComplete *int32 `json:"percentComplete,omitempty"` // RequestedElasticPoolName - READ-ONLY; The name for the elastic pool the database is moving into if available. RequestedElasticPoolName *string `json:"requestedElasticPoolName,omitempty"` // CurrentElasticPoolName - READ-ONLY; The name of the current elastic pool the database is in if available. CurrentElasticPoolName *string `json:"currentElasticPoolName,omitempty"` // CurrentServiceObjective - READ-ONLY; The name of the current service objective if available. CurrentServiceObjective *string `json:"currentServiceObjective,omitempty"` // RequestedServiceObjective - READ-ONLY; The name of the requested service objective if available. RequestedServiceObjective *string `json:"requestedServiceObjective,omitempty"` // ServerName - READ-ONLY; The name of the server the elastic pool is in. ServerName *string `json:"serverName,omitempty"` // StartTime - READ-ONLY; The time the operation started (ISO8601 format). StartTime *date.Time `json:"startTime,omitempty"` // State - READ-ONLY; The current state of the operation. State *string `json:"state,omitempty"` } // ElasticPoolEditionCapability the elastic pool edition capability. type ElasticPoolEditionCapability struct { // Name - READ-ONLY; The elastic pool edition name. Name *string `json:"name,omitempty"` // SupportedElasticPoolPerformanceLevels - READ-ONLY; The list of supported elastic pool DTU levels for the edition. SupportedElasticPoolPerformanceLevels *[]ElasticPoolPerformanceLevelCapability `json:"supportedElasticPoolPerformanceLevels,omitempty"` // ZoneRedundant - READ-ONLY; Whether or not zone redundancy is supported for the edition. ZoneRedundant *bool `json:"zoneRedundant,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ElasticPoolListResult the result of an elastic pool list request. type ElasticPoolListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ElasticPool `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ElasticPoolListResultIterator provides access to a complete listing of ElasticPool values. type ElasticPoolListResultIterator struct { i int page ElasticPoolListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ElasticPoolListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ElasticPoolListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ElasticPoolListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ElasticPoolListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ElasticPoolListResultIterator) Response() ElasticPoolListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ElasticPoolListResultIterator) Value() ElasticPool { if !iter.page.NotDone() { return ElasticPool{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ElasticPoolListResultIterator type. func NewElasticPoolListResultIterator(page ElasticPoolListResultPage) ElasticPoolListResultIterator { return ElasticPoolListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (eplr ElasticPoolListResult) IsEmpty() bool { return eplr.Value == nil || len(*eplr.Value) == 0 } // elasticPoolListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (eplr ElasticPoolListResult) elasticPoolListResultPreparer(ctx context.Context) (*http.Request, error) { if eplr.NextLink == nil || len(to.String(eplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(eplr.NextLink))) } // ElasticPoolListResultPage contains a page of ElasticPool values. type ElasticPoolListResultPage struct { fn func(context.Context, ElasticPoolListResult) (ElasticPoolListResult, error) eplr ElasticPoolListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ElasticPoolListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ElasticPoolListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.eplr) if err != nil { return err } page.eplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ElasticPoolListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ElasticPoolListResultPage) NotDone() bool { return !page.eplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ElasticPoolListResultPage) Response() ElasticPoolListResult { return page.eplr } // Values returns the slice of values for the current page or nil if there are no values. func (page ElasticPoolListResultPage) Values() []ElasticPool { if page.eplr.IsEmpty() { return nil } return *page.eplr.Value } // Creates a new instance of the ElasticPoolListResultPage type. func NewElasticPoolListResultPage(getNextPage func(context.Context, ElasticPoolListResult) (ElasticPoolListResult, error)) ElasticPoolListResultPage { return ElasticPoolListResultPage{fn: getNextPage} } // ElasticPoolOperation a elastic pool operation. type ElasticPoolOperation struct { // ElasticPoolOperationProperties - Resource properties. *ElasticPoolOperationProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ElasticPoolOperation. func (epo ElasticPoolOperation) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if epo.ElasticPoolOperationProperties != nil { objectMap["properties"] = epo.ElasticPoolOperationProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ElasticPoolOperation struct. func (epo *ElasticPoolOperation) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var elasticPoolOperationProperties ElasticPoolOperationProperties err = json.Unmarshal(*v, &elasticPoolOperationProperties) if err != nil { return err } epo.ElasticPoolOperationProperties = &elasticPoolOperationProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } epo.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } epo.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } epo.Type = &typeVar } } } return nil } // ElasticPoolOperationListResult the response to a list elastic pool operations request type ElasticPoolOperationListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ElasticPoolOperation `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ElasticPoolOperationListResultIterator provides access to a complete listing of ElasticPoolOperation // values. type ElasticPoolOperationListResultIterator struct { i int page ElasticPoolOperationListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ElasticPoolOperationListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ElasticPoolOperationListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ElasticPoolOperationListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ElasticPoolOperationListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ElasticPoolOperationListResultIterator) Response() ElasticPoolOperationListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ElasticPoolOperationListResultIterator) Value() ElasticPoolOperation { if !iter.page.NotDone() { return ElasticPoolOperation{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ElasticPoolOperationListResultIterator type. func NewElasticPoolOperationListResultIterator(page ElasticPoolOperationListResultPage) ElasticPoolOperationListResultIterator { return ElasticPoolOperationListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (epolr ElasticPoolOperationListResult) IsEmpty() bool { return epolr.Value == nil || len(*epolr.Value) == 0 } // elasticPoolOperationListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (epolr ElasticPoolOperationListResult) elasticPoolOperationListResultPreparer(ctx context.Context) (*http.Request, error) { if epolr.NextLink == nil || len(to.String(epolr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(epolr.NextLink))) } // ElasticPoolOperationListResultPage contains a page of ElasticPoolOperation values. type ElasticPoolOperationListResultPage struct { fn func(context.Context, ElasticPoolOperationListResult) (ElasticPoolOperationListResult, error) epolr ElasticPoolOperationListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ElasticPoolOperationListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ElasticPoolOperationListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.epolr) if err != nil { return err } page.epolr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ElasticPoolOperationListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ElasticPoolOperationListResultPage) NotDone() bool { return !page.epolr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ElasticPoolOperationListResultPage) Response() ElasticPoolOperationListResult { return page.epolr } // Values returns the slice of values for the current page or nil if there are no values. func (page ElasticPoolOperationListResultPage) Values() []ElasticPoolOperation { if page.epolr.IsEmpty() { return nil } return *page.epolr.Value } // Creates a new instance of the ElasticPoolOperationListResultPage type. func NewElasticPoolOperationListResultPage(getNextPage func(context.Context, ElasticPoolOperationListResult) (ElasticPoolOperationListResult, error)) ElasticPoolOperationListResultPage { return ElasticPoolOperationListResultPage{fn: getNextPage} } // ElasticPoolOperationProperties the properties of a elastic pool operation. type ElasticPoolOperationProperties struct { // ElasticPoolName - READ-ONLY; The name of the elastic pool the operation is being performed on. ElasticPoolName *string `json:"elasticPoolName,omitempty"` // Operation - READ-ONLY; The name of operation. Operation *string `json:"operation,omitempty"` // OperationFriendlyName - READ-ONLY; The friendly name of operation. OperationFriendlyName *string `json:"operationFriendlyName,omitempty"` // PercentComplete - READ-ONLY; The percentage of the operation completed. PercentComplete *int32 `json:"percentComplete,omitempty"` // ServerName - READ-ONLY; The name of the server. ServerName *string `json:"serverName,omitempty"` // StartTime - READ-ONLY; The operation start time. StartTime *date.Time `json:"startTime,omitempty"` // State - READ-ONLY; The operation state. State *string `json:"state,omitempty"` // ErrorCode - READ-ONLY; The operation error code. ErrorCode *int32 `json:"errorCode,omitempty"` // ErrorDescription - READ-ONLY; The operation error description. ErrorDescription *string `json:"errorDescription,omitempty"` // ErrorSeverity - READ-ONLY; The operation error severity. ErrorSeverity *int32 `json:"errorSeverity,omitempty"` // IsUserError - READ-ONLY; Whether or not the error is a user error. IsUserError *bool `json:"isUserError,omitempty"` // EstimatedCompletionTime - READ-ONLY; The estimated completion time of the operation. EstimatedCompletionTime *date.Time `json:"estimatedCompletionTime,omitempty"` // Description - READ-ONLY; The operation description. Description *string `json:"description,omitempty"` // IsCancellable - READ-ONLY; Whether the operation can be cancelled. IsCancellable *bool `json:"isCancellable,omitempty"` } // ElasticPoolPerDatabaseMaxPerformanceLevelCapability the max per-database performance level capability. type ElasticPoolPerDatabaseMaxPerformanceLevelCapability struct { // Limit - READ-ONLY; The maximum performance level per database. Limit *float64 `json:"limit,omitempty"` // Unit - READ-ONLY; Unit type used to measure performance level. Possible values include: 'DTU', 'VCores' Unit PerformanceLevelUnit `json:"unit,omitempty"` // SupportedPerDatabaseMinPerformanceLevels - READ-ONLY; The list of supported min database performance levels. SupportedPerDatabaseMinPerformanceLevels *[]ElasticPoolPerDatabaseMinPerformanceLevelCapability `json:"supportedPerDatabaseMinPerformanceLevels,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ElasticPoolPerDatabaseMinPerformanceLevelCapability the minimum per-database performance level // capability. type ElasticPoolPerDatabaseMinPerformanceLevelCapability struct { // Limit - READ-ONLY; The minimum performance level per database. Limit *float64 `json:"limit,omitempty"` // Unit - READ-ONLY; Unit type used to measure performance level. Possible values include: 'DTU', 'VCores' Unit PerformanceLevelUnit `json:"unit,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ElasticPoolPerDatabaseSettings per database settings of an elastic pool. type ElasticPoolPerDatabaseSettings struct { // MinCapacity - The minimum capacity all databases are guaranteed. MinCapacity *float64 `json:"minCapacity,omitempty"` // MaxCapacity - The maximum capacity any one database can consume. MaxCapacity *float64 `json:"maxCapacity,omitempty"` } // ElasticPoolPerformanceLevelCapability the Elastic Pool performance level capability. type ElasticPoolPerformanceLevelCapability struct { // PerformanceLevel - READ-ONLY; The performance level for the pool. PerformanceLevel *PerformanceLevelCapability `json:"performanceLevel,omitempty"` // Sku - READ-ONLY; The sku. Sku *Sku `json:"sku,omitempty"` // SupportedLicenseTypes - READ-ONLY; List of supported license types. SupportedLicenseTypes *[]LicenseTypeCapability `json:"supportedLicenseTypes,omitempty"` // MaxDatabaseCount - READ-ONLY; The maximum number of databases supported. MaxDatabaseCount *int32 `json:"maxDatabaseCount,omitempty"` // IncludedMaxSize - READ-ONLY; The included (free) max size for this performance level. IncludedMaxSize *MaxSizeCapability `json:"includedMaxSize,omitempty"` // SupportedMaxSizes - READ-ONLY; The list of supported max sizes. SupportedMaxSizes *[]MaxSizeRangeCapability `json:"supportedMaxSizes,omitempty"` // SupportedPerDatabaseMaxSizes - READ-ONLY; The list of supported per database max sizes. SupportedPerDatabaseMaxSizes *[]MaxSizeRangeCapability `json:"supportedPerDatabaseMaxSizes,omitempty"` // SupportedPerDatabaseMaxPerformanceLevels - READ-ONLY; The list of supported per database max performance levels. SupportedPerDatabaseMaxPerformanceLevels *[]ElasticPoolPerDatabaseMaxPerformanceLevelCapability `json:"supportedPerDatabaseMaxPerformanceLevels,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ElasticPoolProperties properties of an elastic pool type ElasticPoolProperties struct { // State - READ-ONLY; The state of the elastic pool. Possible values include: 'ElasticPoolStateCreating', 'ElasticPoolStateReady', 'ElasticPoolStateDisabled' State ElasticPoolState `json:"state,omitempty"` // CreationDate - READ-ONLY; The creation date of the elastic pool (ISO8601 format). CreationDate *date.Time `json:"creationDate,omitempty"` // MaxSizeBytes - The storage limit for the database elastic pool in bytes. MaxSizeBytes *int64 `json:"maxSizeBytes,omitempty"` // PerDatabaseSettings - The per database settings for the elastic pool. PerDatabaseSettings *ElasticPoolPerDatabaseSettings `json:"perDatabaseSettings,omitempty"` // ZoneRedundant - Whether or not this elastic pool is zone redundant, which means the replicas of this elastic pool will be spread across multiple availability zones. ZoneRedundant *bool `json:"zoneRedundant,omitempty"` // LicenseType - The license type to apply for this elastic pool. Possible values include: 'ElasticPoolLicenseTypeLicenseIncluded', 'ElasticPoolLicenseTypeBasePrice' LicenseType ElasticPoolLicenseType `json:"licenseType,omitempty"` } // ElasticPoolsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ElasticPoolsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ElasticPoolsCreateOrUpdateFuture) Result(client ElasticPoolsClient) (ep ElasticPool, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ElasticPoolsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ElasticPoolsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ep.Response.Response, err = future.GetResult(sender); err == nil && ep.Response.Response.StatusCode != http.StatusNoContent { ep, err = client.CreateOrUpdateResponder(ep.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ElasticPoolsCreateOrUpdateFuture", "Result", ep.Response.Response, "Failure responding to request") } } return } // ElasticPoolsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ElasticPoolsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ElasticPoolsDeleteFuture) Result(client ElasticPoolsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ElasticPoolsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ElasticPoolsDeleteFuture") return } ar.Response = future.Response() return } // ElasticPoolsFailoverFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ElasticPoolsFailoverFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ElasticPoolsFailoverFuture) Result(client ElasticPoolsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ElasticPoolsFailoverFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ElasticPoolsFailoverFuture") return } ar.Response = future.Response() return } // ElasticPoolsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ElasticPoolsUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ElasticPoolsUpdateFuture) Result(client ElasticPoolsClient) (ep ElasticPool, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ElasticPoolsUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ElasticPoolsUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ep.Response.Response, err = future.GetResult(sender); err == nil && ep.Response.Response.StatusCode != http.StatusNoContent { ep, err = client.UpdateResponder(ep.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ElasticPoolsUpdateFuture", "Result", ep.Response.Response, "Failure responding to request") } } return } // ElasticPoolUpdate an elastic pool update. type ElasticPoolUpdate struct { Sku *Sku `json:"sku,omitempty"` // ElasticPoolUpdateProperties - Resource properties. *ElasticPoolUpdateProperties `json:"properties,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` } // MarshalJSON is the custom marshaler for ElasticPoolUpdate. func (epu ElasticPoolUpdate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if epu.Sku != nil { objectMap["sku"] = epu.Sku } if epu.ElasticPoolUpdateProperties != nil { objectMap["properties"] = epu.ElasticPoolUpdateProperties } if epu.Tags != nil { objectMap["tags"] = epu.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ElasticPoolUpdate struct. func (epu *ElasticPoolUpdate) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "sku": if v != nil { var sku Sku err = json.Unmarshal(*v, &sku) if err != nil { return err } epu.Sku = &sku } case "properties": if v != nil { var elasticPoolUpdateProperties ElasticPoolUpdateProperties err = json.Unmarshal(*v, &elasticPoolUpdateProperties) if err != nil { return err } epu.ElasticPoolUpdateProperties = &elasticPoolUpdateProperties } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } epu.Tags = tags } } } return nil } // ElasticPoolUpdateProperties properties of an elastic pool type ElasticPoolUpdateProperties struct { // MaxSizeBytes - The storage limit for the database elastic pool in bytes. MaxSizeBytes *int64 `json:"maxSizeBytes,omitempty"` // PerDatabaseSettings - The per database settings for the elastic pool. PerDatabaseSettings *ElasticPoolPerDatabaseSettings `json:"perDatabaseSettings,omitempty"` // ZoneRedundant - Whether or not this elastic pool is zone redundant, which means the replicas of this elastic pool will be spread across multiple availability zones. ZoneRedundant *bool `json:"zoneRedundant,omitempty"` // LicenseType - The license type to apply for this elastic pool. Possible values include: 'ElasticPoolLicenseTypeLicenseIncluded', 'ElasticPoolLicenseTypeBasePrice' LicenseType ElasticPoolLicenseType `json:"licenseType,omitempty"` } // EncryptionProtector the server encryption protector. type EncryptionProtector struct { autorest.Response `json:"-"` // Kind - READ-ONLY; Kind of encryption protector. This is metadata used for the Azure portal experience. Kind *string `json:"kind,omitempty"` // Location - READ-ONLY; Resource location. Location *string `json:"location,omitempty"` // EncryptionProtectorProperties - Resource properties. *EncryptionProtectorProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for EncryptionProtector. func (ep EncryptionProtector) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if ep.EncryptionProtectorProperties != nil { objectMap["properties"] = ep.EncryptionProtectorProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for EncryptionProtector struct. func (ep *EncryptionProtector) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } ep.Kind = &kind } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } ep.Location = &location } case "properties": if v != nil { var encryptionProtectorProperties EncryptionProtectorProperties err = json.Unmarshal(*v, &encryptionProtectorProperties) if err != nil { return err } ep.EncryptionProtectorProperties = &encryptionProtectorProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } ep.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } ep.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } ep.Type = &typeVar } } } return nil } // EncryptionProtectorListResult a list of server encryption protectors. type EncryptionProtectorListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]EncryptionProtector `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // EncryptionProtectorListResultIterator provides access to a complete listing of EncryptionProtector // values. type EncryptionProtectorListResultIterator struct { i int page EncryptionProtectorListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *EncryptionProtectorListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EncryptionProtectorListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *EncryptionProtectorListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter EncryptionProtectorListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter EncryptionProtectorListResultIterator) Response() EncryptionProtectorListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter EncryptionProtectorListResultIterator) Value() EncryptionProtector { if !iter.page.NotDone() { return EncryptionProtector{} } return iter.page.Values()[iter.i] } // Creates a new instance of the EncryptionProtectorListResultIterator type. func NewEncryptionProtectorListResultIterator(page EncryptionProtectorListResultPage) EncryptionProtectorListResultIterator { return EncryptionProtectorListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (eplr EncryptionProtectorListResult) IsEmpty() bool { return eplr.Value == nil || len(*eplr.Value) == 0 } // encryptionProtectorListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (eplr EncryptionProtectorListResult) encryptionProtectorListResultPreparer(ctx context.Context) (*http.Request, error) { if eplr.NextLink == nil || len(to.String(eplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(eplr.NextLink))) } // EncryptionProtectorListResultPage contains a page of EncryptionProtector values. type EncryptionProtectorListResultPage struct { fn func(context.Context, EncryptionProtectorListResult) (EncryptionProtectorListResult, error) eplr EncryptionProtectorListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *EncryptionProtectorListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/EncryptionProtectorListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.eplr) if err != nil { return err } page.eplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *EncryptionProtectorListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page EncryptionProtectorListResultPage) NotDone() bool { return !page.eplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page EncryptionProtectorListResultPage) Response() EncryptionProtectorListResult { return page.eplr } // Values returns the slice of values for the current page or nil if there are no values. func (page EncryptionProtectorListResultPage) Values() []EncryptionProtector { if page.eplr.IsEmpty() { return nil } return *page.eplr.Value } // Creates a new instance of the EncryptionProtectorListResultPage type. func NewEncryptionProtectorListResultPage(getNextPage func(context.Context, EncryptionProtectorListResult) (EncryptionProtectorListResult, error)) EncryptionProtectorListResultPage { return EncryptionProtectorListResultPage{fn: getNextPage} } // EncryptionProtectorProperties properties for an encryption protector execution. type EncryptionProtectorProperties struct { // Subregion - READ-ONLY; Subregion of the encryption protector. Subregion *string `json:"subregion,omitempty"` // ServerKeyName - The name of the server key. ServerKeyName *string `json:"serverKeyName,omitempty"` // ServerKeyType - The encryption protector type like 'ServiceManaged', 'AzureKeyVault'. Possible values include: 'ServiceManaged', 'AzureKeyVault' ServerKeyType ServerKeyType `json:"serverKeyType,omitempty"` // URI - READ-ONLY; The URI of the server key. URI *string `json:"uri,omitempty"` // Thumbprint - READ-ONLY; Thumbprint of the server key. Thumbprint *string `json:"thumbprint,omitempty"` } // EncryptionProtectorsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type EncryptionProtectorsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *EncryptionProtectorsCreateOrUpdateFuture) Result(client EncryptionProtectorsClient) (ep EncryptionProtector, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.EncryptionProtectorsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.EncryptionProtectorsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ep.Response.Response, err = future.GetResult(sender); err == nil && ep.Response.Response.StatusCode != http.StatusNoContent { ep, err = client.CreateOrUpdateResponder(ep.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.EncryptionProtectorsCreateOrUpdateFuture", "Result", ep.Response.Response, "Failure responding to request") } } return } // EncryptionProtectorsRevalidateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type EncryptionProtectorsRevalidateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *EncryptionProtectorsRevalidateFuture) Result(client EncryptionProtectorsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.EncryptionProtectorsRevalidateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.EncryptionProtectorsRevalidateFuture") return } ar.Response = future.Response() return } // ExportRequest export database parameters. type ExportRequest struct { // StorageKeyType - The type of the storage key to use. Possible values include: 'StorageAccessKey', 'SharedAccessKey' StorageKeyType StorageKeyType `json:"storageKeyType,omitempty"` // StorageKey - The storage key to use. If storage key type is SharedAccessKey, it must be preceded with a "?." StorageKey *string `json:"storageKey,omitempty"` // StorageURI - The storage uri to use. StorageURI *string `json:"storageUri,omitempty"` // AdministratorLogin - The name of the SQL administrator. AdministratorLogin *string `json:"administratorLogin,omitempty"` // AdministratorLoginPassword - The password of the SQL administrator. AdministratorLoginPassword *string `json:"administratorLoginPassword,omitempty"` // AuthenticationType - The authentication type. Possible values include: 'SQL', 'ADPassword' AuthenticationType AuthenticationType `json:"authenticationType,omitempty"` } // ExtendedDatabaseBlobAuditingPolicy an extended database blob auditing policy. type ExtendedDatabaseBlobAuditingPolicy struct { autorest.Response `json:"-"` // ExtendedDatabaseBlobAuditingPolicyProperties - Resource properties. *ExtendedDatabaseBlobAuditingPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ExtendedDatabaseBlobAuditingPolicy. func (edbap ExtendedDatabaseBlobAuditingPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if edbap.ExtendedDatabaseBlobAuditingPolicyProperties != nil { objectMap["properties"] = edbap.ExtendedDatabaseBlobAuditingPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ExtendedDatabaseBlobAuditingPolicy struct. func (edbap *ExtendedDatabaseBlobAuditingPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var extendedDatabaseBlobAuditingPolicyProperties ExtendedDatabaseBlobAuditingPolicyProperties err = json.Unmarshal(*v, &extendedDatabaseBlobAuditingPolicyProperties) if err != nil { return err } edbap.ExtendedDatabaseBlobAuditingPolicyProperties = &extendedDatabaseBlobAuditingPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } edbap.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } edbap.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } edbap.Type = &typeVar } } } return nil } // ExtendedDatabaseBlobAuditingPolicyProperties properties of an extended database blob auditing policy. type ExtendedDatabaseBlobAuditingPolicyProperties struct { // PredicateExpression - Specifies condition of where clause when creating an audit. PredicateExpression *string `json:"predicateExpression,omitempty"` // State - Specifies the state of the policy. If state is Enabled, storageEndpoint or isAzureMonitorTargetEnabled are required. Possible values include: 'BlobAuditingPolicyStateEnabled', 'BlobAuditingPolicyStateDisabled' State BlobAuditingPolicyState `json:"state,omitempty"` // StorageEndpoint - Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). If state is Enabled, storageEndpoint is required. StorageEndpoint *string `json:"storageEndpoint,omitempty"` // StorageAccountAccessKey - Specifies the identifier key of the auditing storage account. If state is Enabled and storageEndpoint is specified, storageAccountAccessKey is required. StorageAccountAccessKey *string `json:"storageAccountAccessKey,omitempty"` // RetentionDays - Specifies the number of days to keep in the audit logs in the storage account. RetentionDays *int32 `json:"retentionDays,omitempty"` // AuditActionsAndGroups - Specifies the Actions-Groups and Actions to audit. // // The recommended set of action groups to use is the following combination - this will audit all the queries and stored procedures executed against the database, as well as successful and failed logins: // // BATCH_COMPLETED_GROUP, // SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP, // FAILED_DATABASE_AUTHENTICATION_GROUP. // // This above combination is also the set that is configured by default when enabling auditing from the Azure portal. // // The supported action groups to audit are (note: choose only specific groups that cover your auditing needs. Using unnecessary groups could lead to very large quantities of audit records): // // APPLICATION_ROLE_CHANGE_PASSWORD_GROUP // BACKUP_RESTORE_GROUP // DATABASE_LOGOUT_GROUP // DATABASE_OBJECT_CHANGE_GROUP // DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP // DATABASE_OBJECT_PERMISSION_CHANGE_GROUP // DATABASE_OPERATION_GROUP // DATABASE_PERMISSION_CHANGE_GROUP // DATABASE_PRINCIPAL_CHANGE_GROUP // DATABASE_PRINCIPAL_IMPERSONATION_GROUP // DATABASE_ROLE_MEMBER_CHANGE_GROUP // FAILED_DATABASE_AUTHENTICATION_GROUP // SCHEMA_OBJECT_ACCESS_GROUP // SCHEMA_OBJECT_CHANGE_GROUP // SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP // SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP // SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP // USER_CHANGE_PASSWORD_GROUP // BATCH_STARTED_GROUP // BATCH_COMPLETED_GROUP // // These are groups that cover all sql statements and stored procedures executed against the database, and should not be used in combination with other groups as this will result in duplicate audit logs. // // For more information, see [Database-Level Audit Action Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups). // // For Database auditing policy, specific Actions can also be specified (note that Actions cannot be specified for Server auditing policy). The supported actions to audit are: // SELECT // UPDATE // INSERT // DELETE // EXECUTE // RECEIVE // REFERENCES // // The general form for defining an action to be audited is: // {action} ON {object} BY {principal} // // Note that <object> in the above format can refer to an object like a table, view, or stored procedure, or an entire database or schema. For the latter cases, the forms DATABASE::{db_name} and SCHEMA::{schema_name} are used, respectively. // // For example: // SELECT on dbo.myTable by public // SELECT on DATABASE::myDatabase by public // SELECT on SCHEMA::mySchema by public // // For more information, see [Database-Level Audit Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions) AuditActionsAndGroups *[]string `json:"auditActionsAndGroups,omitempty"` // StorageAccountSubscriptionID - Specifies the blob storage subscription Id. StorageAccountSubscriptionID *uuid.UUID `json:"storageAccountSubscriptionId,omitempty"` // IsStorageSecondaryKeyInUse - Specifies whether storageAccountAccessKey value is the storage's secondary key. IsStorageSecondaryKeyInUse *bool `json:"isStorageSecondaryKeyInUse,omitempty"` // IsAzureMonitorTargetEnabled - Specifies whether audit events are sent to Azure Monitor. // In order to send the events to Azure Monitor, specify 'state' as 'Enabled' and 'isAzureMonitorTargetEnabled' as true. // // When using REST API to configure auditing, Diagnostic Settings with 'SQLSecurityAuditEvents' diagnostic logs category on the database should be also created. // Note that for server level audit you should use the 'master' database as {databaseName}. // // Diagnostic Settings URI format: // PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview // // For more information, see [Diagnostic Settings REST API](https://go.microsoft.com/fwlink/?linkid=2033207) // or [Diagnostic Settings PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043) IsAzureMonitorTargetEnabled *bool `json:"isAzureMonitorTargetEnabled,omitempty"` } // ExtendedServerBlobAuditingPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type ExtendedServerBlobAuditingPoliciesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ExtendedServerBlobAuditingPoliciesCreateOrUpdateFuture) Result(client ExtendedServerBlobAuditingPoliciesClient) (esbap ExtendedServerBlobAuditingPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ExtendedServerBlobAuditingPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ExtendedServerBlobAuditingPoliciesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if esbap.Response.Response, err = future.GetResult(sender); err == nil && esbap.Response.Response.StatusCode != http.StatusNoContent { esbap, err = client.CreateOrUpdateResponder(esbap.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ExtendedServerBlobAuditingPoliciesCreateOrUpdateFuture", "Result", esbap.Response.Response, "Failure responding to request") } } return } // ExtendedServerBlobAuditingPolicy an extended server blob auditing policy. type ExtendedServerBlobAuditingPolicy struct { autorest.Response `json:"-"` // ExtendedServerBlobAuditingPolicyProperties - Resource properties. *ExtendedServerBlobAuditingPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ExtendedServerBlobAuditingPolicy. func (esbap ExtendedServerBlobAuditingPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if esbap.ExtendedServerBlobAuditingPolicyProperties != nil { objectMap["properties"] = esbap.ExtendedServerBlobAuditingPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ExtendedServerBlobAuditingPolicy struct. func (esbap *ExtendedServerBlobAuditingPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var extendedServerBlobAuditingPolicyProperties ExtendedServerBlobAuditingPolicyProperties err = json.Unmarshal(*v, &extendedServerBlobAuditingPolicyProperties) if err != nil { return err } esbap.ExtendedServerBlobAuditingPolicyProperties = &extendedServerBlobAuditingPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } esbap.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } esbap.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } esbap.Type = &typeVar } } } return nil } // ExtendedServerBlobAuditingPolicyProperties properties of an extended server blob auditing policy. type ExtendedServerBlobAuditingPolicyProperties struct { // PredicateExpression - Specifies condition of where clause when creating an audit. PredicateExpression *string `json:"predicateExpression,omitempty"` // State - Specifies the state of the policy. If state is Enabled, storageEndpoint or isAzureMonitorTargetEnabled are required. Possible values include: 'BlobAuditingPolicyStateEnabled', 'BlobAuditingPolicyStateDisabled' State BlobAuditingPolicyState `json:"state,omitempty"` // StorageEndpoint - Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). If state is Enabled, storageEndpoint is required. StorageEndpoint *string `json:"storageEndpoint,omitempty"` // StorageAccountAccessKey - Specifies the identifier key of the auditing storage account. If state is Enabled and storageEndpoint is specified, storageAccountAccessKey is required. StorageAccountAccessKey *string `json:"storageAccountAccessKey,omitempty"` // RetentionDays - Specifies the number of days to keep in the audit logs in the storage account. RetentionDays *int32 `json:"retentionDays,omitempty"` // AuditActionsAndGroups - Specifies the Actions-Groups and Actions to audit. // // The recommended set of action groups to use is the following combination - this will audit all the queries and stored procedures executed against the database, as well as successful and failed logins: // // BATCH_COMPLETED_GROUP, // SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP, // FAILED_DATABASE_AUTHENTICATION_GROUP. // // This above combination is also the set that is configured by default when enabling auditing from the Azure portal. // // The supported action groups to audit are (note: choose only specific groups that cover your auditing needs. Using unnecessary groups could lead to very large quantities of audit records): // // APPLICATION_ROLE_CHANGE_PASSWORD_GROUP // BACKUP_RESTORE_GROUP // DATABASE_LOGOUT_GROUP // DATABASE_OBJECT_CHANGE_GROUP // DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP // DATABASE_OBJECT_PERMISSION_CHANGE_GROUP // DATABASE_OPERATION_GROUP // DATABASE_PERMISSION_CHANGE_GROUP // DATABASE_PRINCIPAL_CHANGE_GROUP // DATABASE_PRINCIPAL_IMPERSONATION_GROUP // DATABASE_ROLE_MEMBER_CHANGE_GROUP // FAILED_DATABASE_AUTHENTICATION_GROUP // SCHEMA_OBJECT_ACCESS_GROUP // SCHEMA_OBJECT_CHANGE_GROUP // SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP // SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP // SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP // USER_CHANGE_PASSWORD_GROUP // BATCH_STARTED_GROUP // BATCH_COMPLETED_GROUP // // These are groups that cover all sql statements and stored procedures executed against the database, and should not be used in combination with other groups as this will result in duplicate audit logs. // // For more information, see [Database-Level Audit Action Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups). // // For Database auditing policy, specific Actions can also be specified (note that Actions cannot be specified for Server auditing policy). The supported actions to audit are: // SELECT // UPDATE // INSERT // DELETE // EXECUTE // RECEIVE // REFERENCES // // The general form for defining an action to be audited is: // {action} ON {object} BY {principal} // // Note that <object> in the above format can refer to an object like a table, view, or stored procedure, or an entire database or schema. For the latter cases, the forms DATABASE::{db_name} and SCHEMA::{schema_name} are used, respectively. // // For example: // SELECT on dbo.myTable by public // SELECT on DATABASE::myDatabase by public // SELECT on SCHEMA::mySchema by public // // For more information, see [Database-Level Audit Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions) AuditActionsAndGroups *[]string `json:"auditActionsAndGroups,omitempty"` // StorageAccountSubscriptionID - Specifies the blob storage subscription Id. StorageAccountSubscriptionID *uuid.UUID `json:"storageAccountSubscriptionId,omitempty"` // IsStorageSecondaryKeyInUse - Specifies whether storageAccountAccessKey value is the storage's secondary key. IsStorageSecondaryKeyInUse *bool `json:"isStorageSecondaryKeyInUse,omitempty"` // IsAzureMonitorTargetEnabled - Specifies whether audit events are sent to Azure Monitor. // In order to send the events to Azure Monitor, specify 'state' as 'Enabled' and 'isAzureMonitorTargetEnabled' as true. // // When using REST API to configure auditing, Diagnostic Settings with 'SQLSecurityAuditEvents' diagnostic logs category on the database should be also created. // Note that for server level audit you should use the 'master' database as {databaseName}. // // Diagnostic Settings URI format: // PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview // // For more information, see [Diagnostic Settings REST API](https://go.microsoft.com/fwlink/?linkid=2033207) // or [Diagnostic Settings PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043) IsAzureMonitorTargetEnabled *bool `json:"isAzureMonitorTargetEnabled,omitempty"` } // FailoverGroup a failover group. type FailoverGroup struct { autorest.Response `json:"-"` // Location - READ-ONLY; Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // FailoverGroupProperties - Resource properties. *FailoverGroupProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for FailoverGroup. func (fg FailoverGroup) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if fg.Tags != nil { objectMap["tags"] = fg.Tags } if fg.FailoverGroupProperties != nil { objectMap["properties"] = fg.FailoverGroupProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for FailoverGroup struct. func (fg *FailoverGroup) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } fg.Location = &location } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } fg.Tags = tags } case "properties": if v != nil { var failoverGroupProperties FailoverGroupProperties err = json.Unmarshal(*v, &failoverGroupProperties) if err != nil { return err } fg.FailoverGroupProperties = &failoverGroupProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } fg.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } fg.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } fg.Type = &typeVar } } } return nil } // FailoverGroupListResult a list of failover groups. type FailoverGroupListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]FailoverGroup `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // FailoverGroupListResultIterator provides access to a complete listing of FailoverGroup values. type FailoverGroupListResultIterator struct { i int page FailoverGroupListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *FailoverGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/FailoverGroupListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *FailoverGroupListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter FailoverGroupListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter FailoverGroupListResultIterator) Response() FailoverGroupListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter FailoverGroupListResultIterator) Value() FailoverGroup { if !iter.page.NotDone() { return FailoverGroup{} } return iter.page.Values()[iter.i] } // Creates a new instance of the FailoverGroupListResultIterator type. func NewFailoverGroupListResultIterator(page FailoverGroupListResultPage) FailoverGroupListResultIterator { return FailoverGroupListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (fglr FailoverGroupListResult) IsEmpty() bool { return fglr.Value == nil || len(*fglr.Value) == 0 } // failoverGroupListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (fglr FailoverGroupListResult) failoverGroupListResultPreparer(ctx context.Context) (*http.Request, error) { if fglr.NextLink == nil || len(to.String(fglr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(fglr.NextLink))) } // FailoverGroupListResultPage contains a page of FailoverGroup values. type FailoverGroupListResultPage struct { fn func(context.Context, FailoverGroupListResult) (FailoverGroupListResult, error) fglr FailoverGroupListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *FailoverGroupListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/FailoverGroupListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.fglr) if err != nil { return err } page.fglr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *FailoverGroupListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page FailoverGroupListResultPage) NotDone() bool { return !page.fglr.IsEmpty() } // Response returns the raw server response from the last page request. func (page FailoverGroupListResultPage) Response() FailoverGroupListResult { return page.fglr } // Values returns the slice of values for the current page or nil if there are no values. func (page FailoverGroupListResultPage) Values() []FailoverGroup { if page.fglr.IsEmpty() { return nil } return *page.fglr.Value } // Creates a new instance of the FailoverGroupListResultPage type. func NewFailoverGroupListResultPage(getNextPage func(context.Context, FailoverGroupListResult) (FailoverGroupListResult, error)) FailoverGroupListResultPage { return FailoverGroupListResultPage{fn: getNextPage} } // FailoverGroupProperties properties of a failover group. type FailoverGroupProperties struct { // ReadWriteEndpoint - Read-write endpoint of the failover group instance. ReadWriteEndpoint *FailoverGroupReadWriteEndpoint `json:"readWriteEndpoint,omitempty"` // ReadOnlyEndpoint - Read-only endpoint of the failover group instance. ReadOnlyEndpoint *FailoverGroupReadOnlyEndpoint `json:"readOnlyEndpoint,omitempty"` // ReplicationRole - READ-ONLY; Local replication role of the failover group instance. Possible values include: 'Primary', 'Secondary' ReplicationRole FailoverGroupReplicationRole `json:"replicationRole,omitempty"` // ReplicationState - READ-ONLY; Replication state of the failover group instance. ReplicationState *string `json:"replicationState,omitempty"` // PartnerServers - List of partner server information for the failover group. PartnerServers *[]PartnerInfo `json:"partnerServers,omitempty"` // Databases - List of databases in the failover group. Databases *[]string `json:"databases,omitempty"` } // FailoverGroupReadOnlyEndpoint read-only endpoint of the failover group instance. type FailoverGroupReadOnlyEndpoint struct { // FailoverPolicy - Failover policy of the read-only endpoint for the failover group. Possible values include: 'ReadOnlyEndpointFailoverPolicyDisabled', 'ReadOnlyEndpointFailoverPolicyEnabled' FailoverPolicy ReadOnlyEndpointFailoverPolicy `json:"failoverPolicy,omitempty"` } // FailoverGroupReadWriteEndpoint read-write endpoint of the failover group instance. type FailoverGroupReadWriteEndpoint struct { // FailoverPolicy - Failover policy of the read-write endpoint for the failover group. If failoverPolicy is Automatic then failoverWithDataLossGracePeriodMinutes is required. Possible values include: 'Manual', 'Automatic' FailoverPolicy ReadWriteEndpointFailoverPolicy `json:"failoverPolicy,omitempty"` // FailoverWithDataLossGracePeriodMinutes - Grace period before failover with data loss is attempted for the read-write endpoint. If failoverPolicy is Automatic then failoverWithDataLossGracePeriodMinutes is required. FailoverWithDataLossGracePeriodMinutes *int32 `json:"failoverWithDataLossGracePeriodMinutes,omitempty"` } // FailoverGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type FailoverGroupsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *FailoverGroupsCreateOrUpdateFuture) Result(client FailoverGroupsClient) (fg FailoverGroup, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.FailoverGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.FailoverGroupsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if fg.Response.Response, err = future.GetResult(sender); err == nil && fg.Response.Response.StatusCode != http.StatusNoContent { fg, err = client.CreateOrUpdateResponder(fg.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.FailoverGroupsCreateOrUpdateFuture", "Result", fg.Response.Response, "Failure responding to request") } } return } // FailoverGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type FailoverGroupsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *FailoverGroupsDeleteFuture) Result(client FailoverGroupsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.FailoverGroupsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.FailoverGroupsDeleteFuture") return } ar.Response = future.Response() return } // FailoverGroupsFailoverFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type FailoverGroupsFailoverFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *FailoverGroupsFailoverFuture) Result(client FailoverGroupsClient) (fg FailoverGroup, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.FailoverGroupsFailoverFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.FailoverGroupsFailoverFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if fg.Response.Response, err = future.GetResult(sender); err == nil && fg.Response.Response.StatusCode != http.StatusNoContent { fg, err = client.FailoverResponder(fg.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.FailoverGroupsFailoverFuture", "Result", fg.Response.Response, "Failure responding to request") } } return } // FailoverGroupsForceFailoverAllowDataLossFuture an abstraction for monitoring and retrieving the results // of a long-running operation. type FailoverGroupsForceFailoverAllowDataLossFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *FailoverGroupsForceFailoverAllowDataLossFuture) Result(client FailoverGroupsClient) (fg FailoverGroup, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.FailoverGroupsForceFailoverAllowDataLossFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.FailoverGroupsForceFailoverAllowDataLossFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if fg.Response.Response, err = future.GetResult(sender); err == nil && fg.Response.Response.StatusCode != http.StatusNoContent { fg, err = client.ForceFailoverAllowDataLossResponder(fg.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.FailoverGroupsForceFailoverAllowDataLossFuture", "Result", fg.Response.Response, "Failure responding to request") } } return } // FailoverGroupsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type FailoverGroupsUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *FailoverGroupsUpdateFuture) Result(client FailoverGroupsClient) (fg FailoverGroup, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.FailoverGroupsUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.FailoverGroupsUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if fg.Response.Response, err = future.GetResult(sender); err == nil && fg.Response.Response.StatusCode != http.StatusNoContent { fg, err = client.UpdateResponder(fg.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.FailoverGroupsUpdateFuture", "Result", fg.Response.Response, "Failure responding to request") } } return } // FailoverGroupUpdate a failover group update request. type FailoverGroupUpdate struct { // FailoverGroupUpdateProperties - Resource properties. *FailoverGroupUpdateProperties `json:"properties,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` } // MarshalJSON is the custom marshaler for FailoverGroupUpdate. func (fgu FailoverGroupUpdate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if fgu.FailoverGroupUpdateProperties != nil { objectMap["properties"] = fgu.FailoverGroupUpdateProperties } if fgu.Tags != nil { objectMap["tags"] = fgu.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for FailoverGroupUpdate struct. func (fgu *FailoverGroupUpdate) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var failoverGroupUpdateProperties FailoverGroupUpdateProperties err = json.Unmarshal(*v, &failoverGroupUpdateProperties) if err != nil { return err } fgu.FailoverGroupUpdateProperties = &failoverGroupUpdateProperties } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } fgu.Tags = tags } } } return nil } // FailoverGroupUpdateProperties properties of a failover group update. type FailoverGroupUpdateProperties struct { // ReadWriteEndpoint - Read-write endpoint of the failover group instance. ReadWriteEndpoint *FailoverGroupReadWriteEndpoint `json:"readWriteEndpoint,omitempty"` // ReadOnlyEndpoint - Read-only endpoint of the failover group instance. ReadOnlyEndpoint *FailoverGroupReadOnlyEndpoint `json:"readOnlyEndpoint,omitempty"` // Databases - List of databases in the failover group. Databases *[]string `json:"databases,omitempty"` } // FirewallRule represents a server firewall rule. type FirewallRule struct { autorest.Response `json:"-"` // Kind - READ-ONLY; Kind of server that contains this firewall rule. Kind *string `json:"kind,omitempty"` // Location - READ-ONLY; Location of the server that contains this firewall rule. Location *string `json:"location,omitempty"` // FirewallRuleProperties - The properties representing the resource. *FirewallRuleProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for FirewallRule. func (fr FirewallRule) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if fr.FirewallRuleProperties != nil { objectMap["properties"] = fr.FirewallRuleProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for FirewallRule struct. func (fr *FirewallRule) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } fr.Kind = &kind } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } fr.Location = &location } case "properties": if v != nil { var firewallRuleProperties FirewallRuleProperties err = json.Unmarshal(*v, &firewallRuleProperties) if err != nil { return err } fr.FirewallRuleProperties = &firewallRuleProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } fr.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } fr.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } fr.Type = &typeVar } } } return nil } // FirewallRuleListResult represents the response to a List Firewall Rules request. type FirewallRuleListResult struct { autorest.Response `json:"-"` // Value - The list of server firewall rules. Value *[]FirewallRule `json:"value,omitempty"` } // FirewallRuleProperties represents the properties of a server firewall rule. type FirewallRuleProperties struct { // StartIPAddress - The start IP address of the firewall rule. Must be IPv4 format. Use value '0.0.0.0' to represent all Azure-internal IP addresses. StartIPAddress *string `json:"startIpAddress,omitempty"` // EndIPAddress - The end IP address of the firewall rule. Must be IPv4 format. Must be greater than or equal to startIpAddress. Use value '0.0.0.0' to represent all Azure-internal IP addresses. EndIPAddress *string `json:"endIpAddress,omitempty"` } // GeoBackupPolicy a database geo backup policy. type GeoBackupPolicy struct { autorest.Response `json:"-"` // GeoBackupPolicyProperties - The properties of the geo backup policy. *GeoBackupPolicyProperties `json:"properties,omitempty"` // Kind - READ-ONLY; Kind of geo backup policy. This is metadata used for the Azure portal experience. Kind *string `json:"kind,omitempty"` // Location - READ-ONLY; Backup policy location. Location *string `json:"location,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for GeoBackupPolicy. func (gbp GeoBackupPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if gbp.GeoBackupPolicyProperties != nil { objectMap["properties"] = gbp.GeoBackupPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for GeoBackupPolicy struct. func (gbp *GeoBackupPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var geoBackupPolicyProperties GeoBackupPolicyProperties err = json.Unmarshal(*v, &geoBackupPolicyProperties) if err != nil { return err } gbp.GeoBackupPolicyProperties = &geoBackupPolicyProperties } case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } gbp.Kind = &kind } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } gbp.Location = &location } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } gbp.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } gbp.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } gbp.Type = &typeVar } } } return nil } // GeoBackupPolicyListResult the response to a list geo backup policies request. type GeoBackupPolicyListResult struct { autorest.Response `json:"-"` // Value - The list of geo backup policies. Value *[]GeoBackupPolicy `json:"value,omitempty"` } // GeoBackupPolicyProperties the properties of the geo backup policy. type GeoBackupPolicyProperties struct { // State - The state of the geo backup policy. Possible values include: 'GeoBackupPolicyStateDisabled', 'GeoBackupPolicyStateEnabled' State GeoBackupPolicyState `json:"state,omitempty"` // StorageType - READ-ONLY; The storage type of the geo backup policy. StorageType *string `json:"storageType,omitempty"` } // ImportExportResponse response for Import/Export Get operation. type ImportExportResponse struct { autorest.Response `json:"-"` // ImportExportResponseProperties - The import/export operation properties. *ImportExportResponseProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ImportExportResponse. func (ier ImportExportResponse) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if ier.ImportExportResponseProperties != nil { objectMap["properties"] = ier.ImportExportResponseProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ImportExportResponse struct. func (ier *ImportExportResponse) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var importExportResponseProperties ImportExportResponseProperties err = json.Unmarshal(*v, &importExportResponseProperties) if err != nil { return err } ier.ImportExportResponseProperties = &importExportResponseProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } ier.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } ier.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } ier.Type = &typeVar } } } return nil } // ImportExportResponseProperties response for Import/Export Status operation. type ImportExportResponseProperties struct { // RequestType - READ-ONLY; The request type of the operation. RequestType *string `json:"requestType,omitempty"` // RequestID - READ-ONLY; The request type of the operation. RequestID *uuid.UUID `json:"requestId,omitempty"` // ServerName - READ-ONLY; The name of the server. ServerName *string `json:"serverName,omitempty"` // DatabaseName - READ-ONLY; The name of the database. DatabaseName *string `json:"databaseName,omitempty"` // Status - READ-ONLY; The status message returned from the server. Status *string `json:"status,omitempty"` // LastModifiedTime - READ-ONLY; The operation status last modified time. LastModifiedTime *string `json:"lastModifiedTime,omitempty"` // QueuedTime - READ-ONLY; The operation queued time. QueuedTime *string `json:"queuedTime,omitempty"` // BlobURI - READ-ONLY; The blob uri. BlobURI *string `json:"blobUri,omitempty"` // ErrorMessage - READ-ONLY; The error message returned from the server. ErrorMessage *string `json:"errorMessage,omitempty"` } // ImportExtensionProperties represents the properties for an import operation type ImportExtensionProperties struct { // OperationMode - The type of import operation being performed. This is always Import. OperationMode *string `json:"operationMode,omitempty"` // StorageKeyType - The type of the storage key to use. Possible values include: 'StorageAccessKey', 'SharedAccessKey' StorageKeyType StorageKeyType `json:"storageKeyType,omitempty"` // StorageKey - The storage key to use. If storage key type is SharedAccessKey, it must be preceded with a "?." StorageKey *string `json:"storageKey,omitempty"` // StorageURI - The storage uri to use. StorageURI *string `json:"storageUri,omitempty"` // AdministratorLogin - The name of the SQL administrator. AdministratorLogin *string `json:"administratorLogin,omitempty"` // AdministratorLoginPassword - The password of the SQL administrator. AdministratorLoginPassword *string `json:"administratorLoginPassword,omitempty"` // AuthenticationType - The authentication type. Possible values include: 'SQL', 'ADPassword' AuthenticationType AuthenticationType `json:"authenticationType,omitempty"` } // ImportExtensionRequest import database parameters. type ImportExtensionRequest struct { // Name - The name of the extension. Name *string `json:"name,omitempty"` // Type - The type of the extension. Type *string `json:"type,omitempty"` // ImportExtensionProperties - Represents the properties of the resource. *ImportExtensionProperties `json:"properties,omitempty"` } // MarshalJSON is the custom marshaler for ImportExtensionRequest. func (ier ImportExtensionRequest) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if ier.Name != nil { objectMap["name"] = ier.Name } if ier.Type != nil { objectMap["type"] = ier.Type } if ier.ImportExtensionProperties != nil { objectMap["properties"] = ier.ImportExtensionProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ImportExtensionRequest struct. func (ier *ImportExtensionRequest) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } ier.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } ier.Type = &typeVar } case "properties": if v != nil { var importExtensionProperties ImportExtensionProperties err = json.Unmarshal(*v, &importExtensionProperties) if err != nil { return err } ier.ImportExtensionProperties = &importExtensionProperties } } } return nil } // ImportRequest import database parameters. type ImportRequest struct { // DatabaseName - The name of the database to import. DatabaseName *string `json:"databaseName,omitempty"` // Edition - The edition for the database being created. // // The list of SKUs may vary by region and support offer. To determine the SKUs (including the SKU name, tier/edition, family, and capacity) that are available to your subscription in an Azure region, use the `Capabilities_ListByLocation` REST API or one of the following commands: // // ```azurecli // az sql db list-editions -l <location> -o table // ```` // // ```powershell // Get-AzSqlServerServiceObjective -Location <location> // ```` // . Possible values include: 'Web', 'Business', 'Basic', 'Standard', 'Premium', 'PremiumRS', 'Free', 'Stretch', 'DataWarehouse', 'System', 'System2', 'GeneralPurpose', 'BusinessCritical', 'Hyperscale' Edition DatabaseEdition `json:"edition,omitempty"` // ServiceObjectiveName - The name of the service objective to assign to the database. Possible values include: 'ServiceObjectiveNameSystem', 'ServiceObjectiveNameSystem0', 'ServiceObjectiveNameSystem1', 'ServiceObjectiveNameSystem2', 'ServiceObjectiveNameSystem3', 'ServiceObjectiveNameSystem4', 'ServiceObjectiveNameSystem2L', 'ServiceObjectiveNameSystem3L', 'ServiceObjectiveNameSystem4L', 'ServiceObjectiveNameFree', 'ServiceObjectiveNameBasic', 'ServiceObjectiveNameS0', 'ServiceObjectiveNameS1', 'ServiceObjectiveNameS2', 'ServiceObjectiveNameS3', 'ServiceObjectiveNameS4', 'ServiceObjectiveNameS6', 'ServiceObjectiveNameS7', 'ServiceObjectiveNameS9', 'ServiceObjectiveNameS12', 'ServiceObjectiveNameP1', 'ServiceObjectiveNameP2', 'ServiceObjectiveNameP3', 'ServiceObjectiveNameP4', 'ServiceObjectiveNameP6', 'ServiceObjectiveNameP11', 'ServiceObjectiveNameP15', 'ServiceObjectiveNamePRS1', 'ServiceObjectiveNamePRS2', 'ServiceObjectiveNamePRS4', 'ServiceObjectiveNamePRS6', 'ServiceObjectiveNameDW100', 'ServiceObjectiveNameDW200', 'ServiceObjectiveNameDW300', 'ServiceObjectiveNameDW400', 'ServiceObjectiveNameDW500', 'ServiceObjectiveNameDW600', 'ServiceObjectiveNameDW1000', 'ServiceObjectiveNameDW1200', 'ServiceObjectiveNameDW1000c', 'ServiceObjectiveNameDW1500', 'ServiceObjectiveNameDW1500c', 'ServiceObjectiveNameDW2000', 'ServiceObjectiveNameDW2000c', 'ServiceObjectiveNameDW3000', 'ServiceObjectiveNameDW2500c', 'ServiceObjectiveNameDW3000c', 'ServiceObjectiveNameDW6000', 'ServiceObjectiveNameDW5000c', 'ServiceObjectiveNameDW6000c', 'ServiceObjectiveNameDW7500c', 'ServiceObjectiveNameDW10000c', 'ServiceObjectiveNameDW15000c', 'ServiceObjectiveNameDW30000c', 'ServiceObjectiveNameDS100', 'ServiceObjectiveNameDS200', 'ServiceObjectiveNameDS300', 'ServiceObjectiveNameDS400', 'ServiceObjectiveNameDS500', 'ServiceObjectiveNameDS600', 'ServiceObjectiveNameDS1000', 'ServiceObjectiveNameDS1200', 'ServiceObjectiveNameDS1500', 'ServiceObjectiveNameDS2000', 'ServiceObjectiveNameElasticPool' ServiceObjectiveName ServiceObjectiveName `json:"serviceObjectiveName,omitempty"` // MaxSizeBytes - The maximum size for the newly imported database. MaxSizeBytes *string `json:"maxSizeBytes,omitempty"` // StorageKeyType - The type of the storage key to use. Possible values include: 'StorageAccessKey', 'SharedAccessKey' StorageKeyType StorageKeyType `json:"storageKeyType,omitempty"` // StorageKey - The storage key to use. If storage key type is SharedAccessKey, it must be preceded with a "?." StorageKey *string `json:"storageKey,omitempty"` // StorageURI - The storage uri to use. StorageURI *string `json:"storageUri,omitempty"` // AdministratorLogin - The name of the SQL administrator. AdministratorLogin *string `json:"administratorLogin,omitempty"` // AdministratorLoginPassword - The password of the SQL administrator. AdministratorLoginPassword *string `json:"administratorLoginPassword,omitempty"` // AuthenticationType - The authentication type. Possible values include: 'SQL', 'ADPassword' AuthenticationType AuthenticationType `json:"authenticationType,omitempty"` } // InstanceFailoverGroup an instance failover group. type InstanceFailoverGroup struct { autorest.Response `json:"-"` // InstanceFailoverGroupProperties - Resource properties. *InstanceFailoverGroupProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for InstanceFailoverGroup. func (ifg InstanceFailoverGroup) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if ifg.InstanceFailoverGroupProperties != nil { objectMap["properties"] = ifg.InstanceFailoverGroupProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for InstanceFailoverGroup struct. func (ifg *InstanceFailoverGroup) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var instanceFailoverGroupProperties InstanceFailoverGroupProperties err = json.Unmarshal(*v, &instanceFailoverGroupProperties) if err != nil { return err } ifg.InstanceFailoverGroupProperties = &instanceFailoverGroupProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } ifg.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } ifg.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } ifg.Type = &typeVar } } } return nil } // InstanceFailoverGroupListResult a list of instance failover groups. type InstanceFailoverGroupListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]InstanceFailoverGroup `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // InstanceFailoverGroupListResultIterator provides access to a complete listing of InstanceFailoverGroup // values. type InstanceFailoverGroupListResultIterator struct { i int page InstanceFailoverGroupListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *InstanceFailoverGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/InstanceFailoverGroupListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *InstanceFailoverGroupListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter InstanceFailoverGroupListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter InstanceFailoverGroupListResultIterator) Response() InstanceFailoverGroupListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter InstanceFailoverGroupListResultIterator) Value() InstanceFailoverGroup { if !iter.page.NotDone() { return InstanceFailoverGroup{} } return iter.page.Values()[iter.i] } // Creates a new instance of the InstanceFailoverGroupListResultIterator type. func NewInstanceFailoverGroupListResultIterator(page InstanceFailoverGroupListResultPage) InstanceFailoverGroupListResultIterator { return InstanceFailoverGroupListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (ifglr InstanceFailoverGroupListResult) IsEmpty() bool { return ifglr.Value == nil || len(*ifglr.Value) == 0 } // instanceFailoverGroupListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (ifglr InstanceFailoverGroupListResult) instanceFailoverGroupListResultPreparer(ctx context.Context) (*http.Request, error) { if ifglr.NextLink == nil || len(to.String(ifglr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(ifglr.NextLink))) } // InstanceFailoverGroupListResultPage contains a page of InstanceFailoverGroup values. type InstanceFailoverGroupListResultPage struct { fn func(context.Context, InstanceFailoverGroupListResult) (InstanceFailoverGroupListResult, error) ifglr InstanceFailoverGroupListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *InstanceFailoverGroupListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/InstanceFailoverGroupListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.ifglr) if err != nil { return err } page.ifglr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *InstanceFailoverGroupListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page InstanceFailoverGroupListResultPage) NotDone() bool { return !page.ifglr.IsEmpty() } // Response returns the raw server response from the last page request. func (page InstanceFailoverGroupListResultPage) Response() InstanceFailoverGroupListResult { return page.ifglr } // Values returns the slice of values for the current page or nil if there are no values. func (page InstanceFailoverGroupListResultPage) Values() []InstanceFailoverGroup { if page.ifglr.IsEmpty() { return nil } return *page.ifglr.Value } // Creates a new instance of the InstanceFailoverGroupListResultPage type. func NewInstanceFailoverGroupListResultPage(getNextPage func(context.Context, InstanceFailoverGroupListResult) (InstanceFailoverGroupListResult, error)) InstanceFailoverGroupListResultPage { return InstanceFailoverGroupListResultPage{fn: getNextPage} } // InstanceFailoverGroupProperties properties of a instance failover group. type InstanceFailoverGroupProperties struct { // ReadWriteEndpoint - Read-write endpoint of the failover group instance. ReadWriteEndpoint *InstanceFailoverGroupReadWriteEndpoint `json:"readWriteEndpoint,omitempty"` // ReadOnlyEndpoint - Read-only endpoint of the failover group instance. ReadOnlyEndpoint *InstanceFailoverGroupReadOnlyEndpoint `json:"readOnlyEndpoint,omitempty"` // ReplicationRole - READ-ONLY; Local replication role of the failover group instance. Possible values include: 'InstanceFailoverGroupReplicationRolePrimary', 'InstanceFailoverGroupReplicationRoleSecondary' ReplicationRole InstanceFailoverGroupReplicationRole `json:"replicationRole,omitempty"` // ReplicationState - READ-ONLY; Replication state of the failover group instance. ReplicationState *string `json:"replicationState,omitempty"` // PartnerRegions - Partner region information for the failover group. PartnerRegions *[]PartnerRegionInfo `json:"partnerRegions,omitempty"` // ManagedInstancePairs - List of managed instance pairs in the failover group. ManagedInstancePairs *[]ManagedInstancePairInfo `json:"managedInstancePairs,omitempty"` } // InstanceFailoverGroupReadOnlyEndpoint read-only endpoint of the failover group instance. type InstanceFailoverGroupReadOnlyEndpoint struct { // FailoverPolicy - Failover policy of the read-only endpoint for the failover group. Possible values include: 'ReadOnlyEndpointFailoverPolicyDisabled', 'ReadOnlyEndpointFailoverPolicyEnabled' FailoverPolicy ReadOnlyEndpointFailoverPolicy `json:"failoverPolicy,omitempty"` } // InstanceFailoverGroupReadWriteEndpoint read-write endpoint of the failover group instance. type InstanceFailoverGroupReadWriteEndpoint struct { // FailoverPolicy - Failover policy of the read-write endpoint for the failover group. If failoverPolicy is Automatic then failoverWithDataLossGracePeriodMinutes is required. Possible values include: 'Manual', 'Automatic' FailoverPolicy ReadWriteEndpointFailoverPolicy `json:"failoverPolicy,omitempty"` // FailoverWithDataLossGracePeriodMinutes - Grace period before failover with data loss is attempted for the read-write endpoint. If failoverPolicy is Automatic then failoverWithDataLossGracePeriodMinutes is required. FailoverWithDataLossGracePeriodMinutes *int32 `json:"failoverWithDataLossGracePeriodMinutes,omitempty"` } // InstanceFailoverGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type InstanceFailoverGroupsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *InstanceFailoverGroupsCreateOrUpdateFuture) Result(client InstanceFailoverGroupsClient) (ifg InstanceFailoverGroup, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.InstanceFailoverGroupsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ifg.Response.Response, err = future.GetResult(sender); err == nil && ifg.Response.Response.StatusCode != http.StatusNoContent { ifg, err = client.CreateOrUpdateResponder(ifg.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsCreateOrUpdateFuture", "Result", ifg.Response.Response, "Failure responding to request") } } return } // InstanceFailoverGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type InstanceFailoverGroupsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *InstanceFailoverGroupsDeleteFuture) Result(client InstanceFailoverGroupsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.InstanceFailoverGroupsDeleteFuture") return } ar.Response = future.Response() return } // InstanceFailoverGroupsFailoverFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type InstanceFailoverGroupsFailoverFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *InstanceFailoverGroupsFailoverFuture) Result(client InstanceFailoverGroupsClient) (ifg InstanceFailoverGroup, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsFailoverFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.InstanceFailoverGroupsFailoverFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ifg.Response.Response, err = future.GetResult(sender); err == nil && ifg.Response.Response.StatusCode != http.StatusNoContent { ifg, err = client.FailoverResponder(ifg.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsFailoverFuture", "Result", ifg.Response.Response, "Failure responding to request") } } return } // InstanceFailoverGroupsForceFailoverAllowDataLossFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type InstanceFailoverGroupsForceFailoverAllowDataLossFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *InstanceFailoverGroupsForceFailoverAllowDataLossFuture) Result(client InstanceFailoverGroupsClient) (ifg InstanceFailoverGroup, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsForceFailoverAllowDataLossFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.InstanceFailoverGroupsForceFailoverAllowDataLossFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ifg.Response.Response, err = future.GetResult(sender); err == nil && ifg.Response.Response.StatusCode != http.StatusNoContent { ifg, err = client.ForceFailoverAllowDataLossResponder(ifg.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstanceFailoverGroupsForceFailoverAllowDataLossFuture", "Result", ifg.Response.Response, "Failure responding to request") } } return } // InstancePool an Azure SQL instance pool. type InstancePool struct { autorest.Response `json:"-"` // Sku - The name and tier of the SKU. Sku *Sku `json:"sku,omitempty"` // InstancePoolProperties - Resource properties. *InstancePoolProperties `json:"properties,omitempty"` // Location - Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for InstancePool. func (IP InstancePool) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if IP.Sku != nil { objectMap["sku"] = IP.Sku } if IP.InstancePoolProperties != nil { objectMap["properties"] = IP.InstancePoolProperties } if IP.Location != nil { objectMap["location"] = IP.Location } if IP.Tags != nil { objectMap["tags"] = IP.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for InstancePool struct. func (IP *InstancePool) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "sku": if v != nil { var sku Sku err = json.Unmarshal(*v, &sku) if err != nil { return err } IP.Sku = &sku } case "properties": if v != nil { var instancePoolProperties InstancePoolProperties err = json.Unmarshal(*v, &instancePoolProperties) if err != nil { return err } IP.InstancePoolProperties = &instancePoolProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } IP.Location = &location } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } IP.Tags = tags } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } IP.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } IP.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } IP.Type = &typeVar } } } return nil } // InstancePoolListResult a list of Azure SQL instance pools. type InstancePoolListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]InstancePool `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // InstancePoolListResultIterator provides access to a complete listing of InstancePool values. type InstancePoolListResultIterator struct { i int page InstancePoolListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *InstancePoolListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/InstancePoolListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *InstancePoolListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter InstancePoolListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter InstancePoolListResultIterator) Response() InstancePoolListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter InstancePoolListResultIterator) Value() InstancePool { if !iter.page.NotDone() { return InstancePool{} } return iter.page.Values()[iter.i] } // Creates a new instance of the InstancePoolListResultIterator type. func NewInstancePoolListResultIterator(page InstancePoolListResultPage) InstancePoolListResultIterator { return InstancePoolListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (iplr InstancePoolListResult) IsEmpty() bool { return iplr.Value == nil || len(*iplr.Value) == 0 } // instancePoolListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (iplr InstancePoolListResult) instancePoolListResultPreparer(ctx context.Context) (*http.Request, error) { if iplr.NextLink == nil || len(to.String(iplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(iplr.NextLink))) } // InstancePoolListResultPage contains a page of InstancePool values. type InstancePoolListResultPage struct { fn func(context.Context, InstancePoolListResult) (InstancePoolListResult, error) iplr InstancePoolListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *InstancePoolListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/InstancePoolListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.iplr) if err != nil { return err } page.iplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *InstancePoolListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page InstancePoolListResultPage) NotDone() bool { return !page.iplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page InstancePoolListResultPage) Response() InstancePoolListResult { return page.iplr } // Values returns the slice of values for the current page or nil if there are no values. func (page InstancePoolListResultPage) Values() []InstancePool { if page.iplr.IsEmpty() { return nil } return *page.iplr.Value } // Creates a new instance of the InstancePoolListResultPage type. func NewInstancePoolListResultPage(getNextPage func(context.Context, InstancePoolListResult) (InstancePoolListResult, error)) InstancePoolListResultPage { return InstancePoolListResultPage{fn: getNextPage} } // InstancePoolProperties properties of an instance pool. type InstancePoolProperties struct { // SubnetID - Resource ID of the subnet to place this instance pool in. SubnetID *string `json:"subnetId,omitempty"` // VCores - Count of vCores belonging to this instance pool. VCores *int32 `json:"vCores,omitempty"` // LicenseType - The license type. Possible values are 'LicenseIncluded' (price for SQL license is included) and 'BasePrice' (without SQL license price). Possible values include: 'InstancePoolLicenseTypeLicenseIncluded', 'InstancePoolLicenseTypeBasePrice' LicenseType InstancePoolLicenseType `json:"licenseType,omitempty"` } // InstancePoolsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type InstancePoolsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *InstancePoolsCreateOrUpdateFuture) Result(client InstancePoolsClient) (IP InstancePool, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstancePoolsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.InstancePoolsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if IP.Response.Response, err = future.GetResult(sender); err == nil && IP.Response.Response.StatusCode != http.StatusNoContent { IP, err = client.CreateOrUpdateResponder(IP.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstancePoolsCreateOrUpdateFuture", "Result", IP.Response.Response, "Failure responding to request") } } return } // InstancePoolsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type InstancePoolsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *InstancePoolsDeleteFuture) Result(client InstancePoolsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstancePoolsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.InstancePoolsDeleteFuture") return } ar.Response = future.Response() return } // InstancePoolsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type InstancePoolsUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *InstancePoolsUpdateFuture) Result(client InstancePoolsClient) (IP InstancePool, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstancePoolsUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.InstancePoolsUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if IP.Response.Response, err = future.GetResult(sender); err == nil && IP.Response.Response.StatusCode != http.StatusNoContent { IP, err = client.UpdateResponder(IP.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.InstancePoolsUpdateFuture", "Result", IP.Response.Response, "Failure responding to request") } } return } // InstancePoolUpdate an update to an Instance pool. type InstancePoolUpdate struct { // Tags - Resource tags. Tags map[string]*string `json:"tags"` } // MarshalJSON is the custom marshaler for InstancePoolUpdate. func (ipu InstancePoolUpdate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if ipu.Tags != nil { objectMap["tags"] = ipu.Tags } return json.Marshal(objectMap) } // Job a job. type Job struct { autorest.Response `json:"-"` // JobProperties - Resource properties. *JobProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for Job. func (j Job) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if j.JobProperties != nil { objectMap["properties"] = j.JobProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for Job struct. func (j *Job) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var jobProperties JobProperties err = json.Unmarshal(*v, &jobProperties) if err != nil { return err } j.JobProperties = &jobProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } j.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } j.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } j.Type = &typeVar } } } return nil } // JobAgent an Azure SQL job agent. type JobAgent struct { autorest.Response `json:"-"` // Sku - The name and tier of the SKU. Sku *Sku `json:"sku,omitempty"` // JobAgentProperties - Resource properties. *JobAgentProperties `json:"properties,omitempty"` // Location - Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for JobAgent. func (ja JobAgent) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if ja.Sku != nil { objectMap["sku"] = ja.Sku } if ja.JobAgentProperties != nil { objectMap["properties"] = ja.JobAgentProperties } if ja.Location != nil { objectMap["location"] = ja.Location } if ja.Tags != nil { objectMap["tags"] = ja.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for JobAgent struct. func (ja *JobAgent) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "sku": if v != nil { var sku Sku err = json.Unmarshal(*v, &sku) if err != nil { return err } ja.Sku = &sku } case "properties": if v != nil { var jobAgentProperties JobAgentProperties err = json.Unmarshal(*v, &jobAgentProperties) if err != nil { return err } ja.JobAgentProperties = &jobAgentProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } ja.Location = &location } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } ja.Tags = tags } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } ja.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } ja.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } ja.Type = &typeVar } } } return nil } // JobAgentListResult a list of Azure SQL job agents. type JobAgentListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]JobAgent `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // JobAgentListResultIterator provides access to a complete listing of JobAgent values. type JobAgentListResultIterator struct { i int page JobAgentListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *JobAgentListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobAgentListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *JobAgentListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter JobAgentListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter JobAgentListResultIterator) Response() JobAgentListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter JobAgentListResultIterator) Value() JobAgent { if !iter.page.NotDone() { return JobAgent{} } return iter.page.Values()[iter.i] } // Creates a new instance of the JobAgentListResultIterator type. func NewJobAgentListResultIterator(page JobAgentListResultPage) JobAgentListResultIterator { return JobAgentListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (jalr JobAgentListResult) IsEmpty() bool { return jalr.Value == nil || len(*jalr.Value) == 0 } // jobAgentListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (jalr JobAgentListResult) jobAgentListResultPreparer(ctx context.Context) (*http.Request, error) { if jalr.NextLink == nil || len(to.String(jalr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(jalr.NextLink))) } // JobAgentListResultPage contains a page of JobAgent values. type JobAgentListResultPage struct { fn func(context.Context, JobAgentListResult) (JobAgentListResult, error) jalr JobAgentListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *JobAgentListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobAgentListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.jalr) if err != nil { return err } page.jalr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *JobAgentListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page JobAgentListResultPage) NotDone() bool { return !page.jalr.IsEmpty() } // Response returns the raw server response from the last page request. func (page JobAgentListResultPage) Response() JobAgentListResult { return page.jalr } // Values returns the slice of values for the current page or nil if there are no values. func (page JobAgentListResultPage) Values() []JobAgent { if page.jalr.IsEmpty() { return nil } return *page.jalr.Value } // Creates a new instance of the JobAgentListResultPage type. func NewJobAgentListResultPage(getNextPage func(context.Context, JobAgentListResult) (JobAgentListResult, error)) JobAgentListResultPage { return JobAgentListResultPage{fn: getNextPage} } // JobAgentProperties properties of a job agent. type JobAgentProperties struct { // DatabaseID - Resource ID of the database to store job metadata in. DatabaseID *string `json:"databaseId,omitempty"` // State - READ-ONLY; The state of the job agent. Possible values include: 'JobAgentStateCreating', 'JobAgentStateReady', 'JobAgentStateUpdating', 'JobAgentStateDeleting', 'JobAgentStateDisabled' State JobAgentState `json:"state,omitempty"` } // JobAgentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type JobAgentsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *JobAgentsCreateOrUpdateFuture) Result(client JobAgentsClient) (ja JobAgent, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.JobAgentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.JobAgentsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ja.Response.Response, err = future.GetResult(sender); err == nil && ja.Response.Response.StatusCode != http.StatusNoContent { ja, err = client.CreateOrUpdateResponder(ja.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.JobAgentsCreateOrUpdateFuture", "Result", ja.Response.Response, "Failure responding to request") } } return } // JobAgentsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type JobAgentsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *JobAgentsDeleteFuture) Result(client JobAgentsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.JobAgentsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.JobAgentsDeleteFuture") return } ar.Response = future.Response() return } // JobAgentsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type JobAgentsUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *JobAgentsUpdateFuture) Result(client JobAgentsClient) (ja JobAgent, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.JobAgentsUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.JobAgentsUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ja.Response.Response, err = future.GetResult(sender); err == nil && ja.Response.Response.StatusCode != http.StatusNoContent { ja, err = client.UpdateResponder(ja.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.JobAgentsUpdateFuture", "Result", ja.Response.Response, "Failure responding to request") } } return } // JobAgentUpdate an update to an Azure SQL job agent. type JobAgentUpdate struct { // Tags - Resource tags. Tags map[string]*string `json:"tags"` } // MarshalJSON is the custom marshaler for JobAgentUpdate. func (jau JobAgentUpdate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if jau.Tags != nil { objectMap["tags"] = jau.Tags } return json.Marshal(objectMap) } // JobCredential a stored credential that can be used by a job to connect to target databases. type JobCredential struct { autorest.Response `json:"-"` // JobCredentialProperties - Resource properties. *JobCredentialProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for JobCredential. func (jc JobCredential) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if jc.JobCredentialProperties != nil { objectMap["properties"] = jc.JobCredentialProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for JobCredential struct. func (jc *JobCredential) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var jobCredentialProperties JobCredentialProperties err = json.Unmarshal(*v, &jobCredentialProperties) if err != nil { return err } jc.JobCredentialProperties = &jobCredentialProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } jc.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } jc.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } jc.Type = &typeVar } } } return nil } // JobCredentialListResult a list of job credentials. type JobCredentialListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]JobCredential `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // JobCredentialListResultIterator provides access to a complete listing of JobCredential values. type JobCredentialListResultIterator struct { i int page JobCredentialListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *JobCredentialListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobCredentialListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *JobCredentialListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter JobCredentialListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter JobCredentialListResultIterator) Response() JobCredentialListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter JobCredentialListResultIterator) Value() JobCredential { if !iter.page.NotDone() { return JobCredential{} } return iter.page.Values()[iter.i] } // Creates a new instance of the JobCredentialListResultIterator type. func NewJobCredentialListResultIterator(page JobCredentialListResultPage) JobCredentialListResultIterator { return JobCredentialListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (jclr JobCredentialListResult) IsEmpty() bool { return jclr.Value == nil || len(*jclr.Value) == 0 } // jobCredentialListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (jclr JobCredentialListResult) jobCredentialListResultPreparer(ctx context.Context) (*http.Request, error) { if jclr.NextLink == nil || len(to.String(jclr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(jclr.NextLink))) } // JobCredentialListResultPage contains a page of JobCredential values. type JobCredentialListResultPage struct { fn func(context.Context, JobCredentialListResult) (JobCredentialListResult, error) jclr JobCredentialListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *JobCredentialListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobCredentialListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.jclr) if err != nil { return err } page.jclr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *JobCredentialListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page JobCredentialListResultPage) NotDone() bool { return !page.jclr.IsEmpty() } // Response returns the raw server response from the last page request. func (page JobCredentialListResultPage) Response() JobCredentialListResult { return page.jclr } // Values returns the slice of values for the current page or nil if there are no values. func (page JobCredentialListResultPage) Values() []JobCredential { if page.jclr.IsEmpty() { return nil } return *page.jclr.Value } // Creates a new instance of the JobCredentialListResultPage type. func NewJobCredentialListResultPage(getNextPage func(context.Context, JobCredentialListResult) (JobCredentialListResult, error)) JobCredentialListResultPage { return JobCredentialListResultPage{fn: getNextPage} } // JobCredentialProperties properties of a job credential. type JobCredentialProperties struct { // Username - The credential user name. Username *string `json:"username,omitempty"` // Password - The credential password. Password *string `json:"password,omitempty"` } // JobExecution an execution of a job type JobExecution struct { autorest.Response `json:"-"` // JobExecutionProperties - Resource properties. *JobExecutionProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for JobExecution. func (je JobExecution) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if je.JobExecutionProperties != nil { objectMap["properties"] = je.JobExecutionProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for JobExecution struct. func (je *JobExecution) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var jobExecutionProperties JobExecutionProperties err = json.Unmarshal(*v, &jobExecutionProperties) if err != nil { return err } je.JobExecutionProperties = &jobExecutionProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } je.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } je.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } je.Type = &typeVar } } } return nil } // JobExecutionListResult a list of job executions. type JobExecutionListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]JobExecution `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // JobExecutionListResultIterator provides access to a complete listing of JobExecution values. type JobExecutionListResultIterator struct { i int page JobExecutionListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *JobExecutionListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobExecutionListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *JobExecutionListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter JobExecutionListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter JobExecutionListResultIterator) Response() JobExecutionListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter JobExecutionListResultIterator) Value() JobExecution { if !iter.page.NotDone() { return JobExecution{} } return iter.page.Values()[iter.i] } // Creates a new instance of the JobExecutionListResultIterator type. func NewJobExecutionListResultIterator(page JobExecutionListResultPage) JobExecutionListResultIterator { return JobExecutionListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (jelr JobExecutionListResult) IsEmpty() bool { return jelr.Value == nil || len(*jelr.Value) == 0 } // jobExecutionListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (jelr JobExecutionListResult) jobExecutionListResultPreparer(ctx context.Context) (*http.Request, error) { if jelr.NextLink == nil || len(to.String(jelr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(jelr.NextLink))) } // JobExecutionListResultPage contains a page of JobExecution values. type JobExecutionListResultPage struct { fn func(context.Context, JobExecutionListResult) (JobExecutionListResult, error) jelr JobExecutionListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *JobExecutionListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobExecutionListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.jelr) if err != nil { return err } page.jelr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *JobExecutionListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page JobExecutionListResultPage) NotDone() bool { return !page.jelr.IsEmpty() } // Response returns the raw server response from the last page request. func (page JobExecutionListResultPage) Response() JobExecutionListResult { return page.jelr } // Values returns the slice of values for the current page or nil if there are no values. func (page JobExecutionListResultPage) Values() []JobExecution { if page.jelr.IsEmpty() { return nil } return *page.jelr.Value } // Creates a new instance of the JobExecutionListResultPage type. func NewJobExecutionListResultPage(getNextPage func(context.Context, JobExecutionListResult) (JobExecutionListResult, error)) JobExecutionListResultPage { return JobExecutionListResultPage{fn: getNextPage} } // JobExecutionProperties properties for an Azure SQL Database Elastic job execution. type JobExecutionProperties struct { // JobVersion - READ-ONLY; The job version number. JobVersion *int32 `json:"jobVersion,omitempty"` // StepName - READ-ONLY; The job step name. StepName *string `json:"stepName,omitempty"` // StepID - READ-ONLY; The job step id. StepID *int32 `json:"stepId,omitempty"` // JobExecutionID - READ-ONLY; The unique identifier of the job execution. JobExecutionID *uuid.UUID `json:"jobExecutionId,omitempty"` // Lifecycle - READ-ONLY; The detailed state of the job execution. Possible values include: 'Created', 'InProgress', 'WaitingForChildJobExecutions', 'WaitingForRetry', 'Succeeded', 'SucceededWithSkipped', 'Failed', 'TimedOut', 'Canceled', 'Skipped' Lifecycle JobExecutionLifecycle `json:"lifecycle,omitempty"` // ProvisioningState - READ-ONLY; The ARM provisioning state of the job execution. Possible values include: 'ProvisioningStateCreated', 'ProvisioningStateInProgress', 'ProvisioningStateSucceeded', 'ProvisioningStateFailed', 'ProvisioningStateCanceled' ProvisioningState ProvisioningState `json:"provisioningState,omitempty"` // CreateTime - READ-ONLY; The time that the job execution was created. CreateTime *date.Time `json:"createTime,omitempty"` // StartTime - READ-ONLY; The time that the job execution started. StartTime *date.Time `json:"startTime,omitempty"` // EndTime - READ-ONLY; The time that the job execution completed. EndTime *date.Time `json:"endTime,omitempty"` // CurrentAttempts - Number of times the job execution has been attempted. CurrentAttempts *int32 `json:"currentAttempts,omitempty"` // CurrentAttemptStartTime - READ-ONLY; Start time of the current attempt. CurrentAttemptStartTime *date.Time `json:"currentAttemptStartTime,omitempty"` // LastMessage - READ-ONLY; The last status or error message. LastMessage *string `json:"lastMessage,omitempty"` // Target - READ-ONLY; The target that this execution is executed on. Target *JobExecutionTarget `json:"target,omitempty"` } // JobExecutionsCreateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type JobExecutionsCreateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *JobExecutionsCreateFuture) Result(client JobExecutionsClient) (je JobExecution, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.JobExecutionsCreateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.JobExecutionsCreateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if je.Response.Response, err = future.GetResult(sender); err == nil && je.Response.Response.StatusCode != http.StatusNoContent { je, err = client.CreateResponder(je.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.JobExecutionsCreateFuture", "Result", je.Response.Response, "Failure responding to request") } } return } // JobExecutionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type JobExecutionsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *JobExecutionsCreateOrUpdateFuture) Result(client JobExecutionsClient) (je JobExecution, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.JobExecutionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.JobExecutionsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if je.Response.Response, err = future.GetResult(sender); err == nil && je.Response.Response.StatusCode != http.StatusNoContent { je, err = client.CreateOrUpdateResponder(je.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.JobExecutionsCreateOrUpdateFuture", "Result", je.Response.Response, "Failure responding to request") } } return } // JobExecutionTarget the target that a job execution is executed on. type JobExecutionTarget struct { // Type - READ-ONLY; The type of the target. Possible values include: 'JobTargetTypeTargetGroup', 'JobTargetTypeSQLDatabase', 'JobTargetTypeSQLElasticPool', 'JobTargetTypeSQLShardMap', 'JobTargetTypeSQLServer' Type JobTargetType `json:"type,omitempty"` // ServerName - READ-ONLY; The server name. ServerName *string `json:"serverName,omitempty"` // DatabaseName - READ-ONLY; The database name. DatabaseName *string `json:"databaseName,omitempty"` } // JobListResult a list of jobs. type JobListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]Job `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // JobListResultIterator provides access to a complete listing of Job values. type JobListResultIterator struct { i int page JobListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *JobListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *JobListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter JobListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter JobListResultIterator) Response() JobListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter JobListResultIterator) Value() Job { if !iter.page.NotDone() { return Job{} } return iter.page.Values()[iter.i] } // Creates a new instance of the JobListResultIterator type. func NewJobListResultIterator(page JobListResultPage) JobListResultIterator { return JobListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (jlr JobListResult) IsEmpty() bool { return jlr.Value == nil || len(*jlr.Value) == 0 } // jobListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (jlr JobListResult) jobListResultPreparer(ctx context.Context) (*http.Request, error) { if jlr.NextLink == nil || len(to.String(jlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(jlr.NextLink))) } // JobListResultPage contains a page of Job values. type JobListResultPage struct { fn func(context.Context, JobListResult) (JobListResult, error) jlr JobListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *JobListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.jlr) if err != nil { return err } page.jlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *JobListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page JobListResultPage) NotDone() bool { return !page.jlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page JobListResultPage) Response() JobListResult { return page.jlr } // Values returns the slice of values for the current page or nil if there are no values. func (page JobListResultPage) Values() []Job { if page.jlr.IsEmpty() { return nil } return *page.jlr.Value } // Creates a new instance of the JobListResultPage type. func NewJobListResultPage(getNextPage func(context.Context, JobListResult) (JobListResult, error)) JobListResultPage { return JobListResultPage{fn: getNextPage} } // JobProperties properties of a job. type JobProperties struct { // Description - User-defined description of the job. Description *string `json:"description,omitempty"` // Version - READ-ONLY; The job version number. Version *int32 `json:"version,omitempty"` // Schedule - Schedule properties of the job. Schedule *JobSchedule `json:"schedule,omitempty"` } // JobSchedule scheduling properties of a job. type JobSchedule struct { // StartTime - Schedule start time. StartTime *date.Time `json:"startTime,omitempty"` // EndTime - Schedule end time. EndTime *date.Time `json:"endTime,omitempty"` // Type - Schedule interval type. Possible values include: 'Once', 'Recurring' Type JobScheduleType `json:"type,omitempty"` // Enabled - Whether or not the schedule is enabled. Enabled *bool `json:"enabled,omitempty"` // Interval - Value of the schedule's recurring interval, if the schedule type is recurring. ISO8601 duration format. Interval *string `json:"interval,omitempty"` } // JobStep a job step. type JobStep struct { autorest.Response `json:"-"` // JobStepProperties - Resource properties. *JobStepProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for JobStep. func (js JobStep) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if js.JobStepProperties != nil { objectMap["properties"] = js.JobStepProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for JobStep struct. func (js *JobStep) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var jobStepProperties JobStepProperties err = json.Unmarshal(*v, &jobStepProperties) if err != nil { return err } js.JobStepProperties = &jobStepProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } js.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } js.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } js.Type = &typeVar } } } return nil } // JobStepAction the action to be executed by a job step. type JobStepAction struct { // Type - Type of action being executed by the job step. Possible values include: 'TSQL' Type JobStepActionType `json:"type,omitempty"` // Source - The source of the action to execute. Possible values include: 'Inline' Source JobStepActionSource `json:"source,omitempty"` // Value - The action value, for example the text of the T-SQL script to execute. Value *string `json:"value,omitempty"` } // JobStepExecutionOptions the execution options of a job step. type JobStepExecutionOptions struct { // TimeoutSeconds - Execution timeout for the job step. TimeoutSeconds *int32 `json:"timeoutSeconds,omitempty"` // RetryAttempts - Maximum number of times the job step will be reattempted if the first attempt fails. RetryAttempts *int32 `json:"retryAttempts,omitempty"` // InitialRetryIntervalSeconds - Initial delay between retries for job step execution. InitialRetryIntervalSeconds *int32 `json:"initialRetryIntervalSeconds,omitempty"` // MaximumRetryIntervalSeconds - The maximum amount of time to wait between retries for job step execution. MaximumRetryIntervalSeconds *int32 `json:"maximumRetryIntervalSeconds,omitempty"` // RetryIntervalBackoffMultiplier - The backoff multiplier for the time between retries. RetryIntervalBackoffMultiplier *float64 `json:"retryIntervalBackoffMultiplier,omitempty"` } // JobStepListResult a list of job steps. type JobStepListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]JobStep `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // JobStepListResultIterator provides access to a complete listing of JobStep values. type JobStepListResultIterator struct { i int page JobStepListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *JobStepListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobStepListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *JobStepListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter JobStepListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter JobStepListResultIterator) Response() JobStepListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter JobStepListResultIterator) Value() JobStep { if !iter.page.NotDone() { return JobStep{} } return iter.page.Values()[iter.i] } // Creates a new instance of the JobStepListResultIterator type. func NewJobStepListResultIterator(page JobStepListResultPage) JobStepListResultIterator { return JobStepListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (jslr JobStepListResult) IsEmpty() bool { return jslr.Value == nil || len(*jslr.Value) == 0 } // jobStepListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (jslr JobStepListResult) jobStepListResultPreparer(ctx context.Context) (*http.Request, error) { if jslr.NextLink == nil || len(to.String(jslr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(jslr.NextLink))) } // JobStepListResultPage contains a page of JobStep values. type JobStepListResultPage struct { fn func(context.Context, JobStepListResult) (JobStepListResult, error) jslr JobStepListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *JobStepListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobStepListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.jslr) if err != nil { return err } page.jslr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *JobStepListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page JobStepListResultPage) NotDone() bool { return !page.jslr.IsEmpty() } // Response returns the raw server response from the last page request. func (page JobStepListResultPage) Response() JobStepListResult { return page.jslr } // Values returns the slice of values for the current page or nil if there are no values. func (page JobStepListResultPage) Values() []JobStep { if page.jslr.IsEmpty() { return nil } return *page.jslr.Value } // Creates a new instance of the JobStepListResultPage type. func NewJobStepListResultPage(getNextPage func(context.Context, JobStepListResult) (JobStepListResult, error)) JobStepListResultPage { return JobStepListResultPage{fn: getNextPage} } // JobStepOutput the output configuration of a job step. type JobStepOutput struct { // Type - The output destination type. Possible values include: 'SQLDatabase' Type JobStepOutputType `json:"type,omitempty"` // SubscriptionID - The output destination subscription id. SubscriptionID *uuid.UUID `json:"subscriptionId,omitempty"` // ResourceGroupName - The output destination resource group. ResourceGroupName *string `json:"resourceGroupName,omitempty"` // ServerName - The output destination server name. ServerName *string `json:"serverName,omitempty"` // DatabaseName - The output destination database. DatabaseName *string `json:"databaseName,omitempty"` // SchemaName - The output destination schema. SchemaName *string `json:"schemaName,omitempty"` // TableName - The output destination table. TableName *string `json:"tableName,omitempty"` // Credential - The resource ID of the credential to use to connect to the output destination. Credential *string `json:"credential,omitempty"` } // JobStepProperties properties of a job step. type JobStepProperties struct { // StepID - The job step's index within the job. If not specified when creating the job step, it will be created as the last step. If not specified when updating the job step, the step id is not modified. StepID *int32 `json:"stepId,omitempty"` // TargetGroup - The resource ID of the target group that the job step will be executed on. TargetGroup *string `json:"targetGroup,omitempty"` // Credential - The resource ID of the job credential that will be used to connect to the targets. Credential *string `json:"credential,omitempty"` // Action - The action payload of the job step. Action *JobStepAction `json:"action,omitempty"` // Output - Output destination properties of the job step. Output *JobStepOutput `json:"output,omitempty"` // ExecutionOptions - Execution options for the job step. ExecutionOptions *JobStepExecutionOptions `json:"executionOptions,omitempty"` } // JobTarget a job target, for example a specific database or a container of databases that is evaluated // during job execution. type JobTarget struct { // MembershipType - Whether the target is included or excluded from the group. Possible values include: 'Include', 'Exclude' MembershipType JobTargetGroupMembershipType `json:"membershipType,omitempty"` // Type - The target type. Possible values include: 'JobTargetTypeTargetGroup', 'JobTargetTypeSQLDatabase', 'JobTargetTypeSQLElasticPool', 'JobTargetTypeSQLShardMap', 'JobTargetTypeSQLServer' Type JobTargetType `json:"type,omitempty"` // ServerName - The target server name. ServerName *string `json:"serverName,omitempty"` // DatabaseName - The target database name. DatabaseName *string `json:"databaseName,omitempty"` // ElasticPoolName - The target elastic pool name. ElasticPoolName *string `json:"elasticPoolName,omitempty"` // ShardMapName - The target shard map. ShardMapName *string `json:"shardMapName,omitempty"` // RefreshCredential - The resource ID of the credential that is used during job execution to connect to the target and determine the list of databases inside the target. RefreshCredential *string `json:"refreshCredential,omitempty"` } // JobTargetGroup a group of job targets. type JobTargetGroup struct { autorest.Response `json:"-"` // JobTargetGroupProperties - Resource properties. *JobTargetGroupProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for JobTargetGroup. func (jtg JobTargetGroup) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if jtg.JobTargetGroupProperties != nil { objectMap["properties"] = jtg.JobTargetGroupProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for JobTargetGroup struct. func (jtg *JobTargetGroup) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var jobTargetGroupProperties JobTargetGroupProperties err = json.Unmarshal(*v, &jobTargetGroupProperties) if err != nil { return err } jtg.JobTargetGroupProperties = &jobTargetGroupProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } jtg.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } jtg.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } jtg.Type = &typeVar } } } return nil } // JobTargetGroupListResult a list of target groups. type JobTargetGroupListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]JobTargetGroup `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // JobTargetGroupListResultIterator provides access to a complete listing of JobTargetGroup values. type JobTargetGroupListResultIterator struct { i int page JobTargetGroupListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *JobTargetGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobTargetGroupListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *JobTargetGroupListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter JobTargetGroupListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter JobTargetGroupListResultIterator) Response() JobTargetGroupListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter JobTargetGroupListResultIterator) Value() JobTargetGroup { if !iter.page.NotDone() { return JobTargetGroup{} } return iter.page.Values()[iter.i] } // Creates a new instance of the JobTargetGroupListResultIterator type. func NewJobTargetGroupListResultIterator(page JobTargetGroupListResultPage) JobTargetGroupListResultIterator { return JobTargetGroupListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (jtglr JobTargetGroupListResult) IsEmpty() bool { return jtglr.Value == nil || len(*jtglr.Value) == 0 } // jobTargetGroupListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (jtglr JobTargetGroupListResult) jobTargetGroupListResultPreparer(ctx context.Context) (*http.Request, error) { if jtglr.NextLink == nil || len(to.String(jtglr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(jtglr.NextLink))) } // JobTargetGroupListResultPage contains a page of JobTargetGroup values. type JobTargetGroupListResultPage struct { fn func(context.Context, JobTargetGroupListResult) (JobTargetGroupListResult, error) jtglr JobTargetGroupListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *JobTargetGroupListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobTargetGroupListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.jtglr) if err != nil { return err } page.jtglr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *JobTargetGroupListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page JobTargetGroupListResultPage) NotDone() bool { return !page.jtglr.IsEmpty() } // Response returns the raw server response from the last page request. func (page JobTargetGroupListResultPage) Response() JobTargetGroupListResult { return page.jtglr } // Values returns the slice of values for the current page or nil if there are no values. func (page JobTargetGroupListResultPage) Values() []JobTargetGroup { if page.jtglr.IsEmpty() { return nil } return *page.jtglr.Value } // Creates a new instance of the JobTargetGroupListResultPage type. func NewJobTargetGroupListResultPage(getNextPage func(context.Context, JobTargetGroupListResult) (JobTargetGroupListResult, error)) JobTargetGroupListResultPage { return JobTargetGroupListResultPage{fn: getNextPage} } // JobTargetGroupProperties properties of job target group. type JobTargetGroupProperties struct { // Members - Members of the target group. Members *[]JobTarget `json:"members,omitempty"` } // JobVersion a job version. type JobVersion struct { autorest.Response `json:"-"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // JobVersionListResult a list of job versions. type JobVersionListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]JobVersion `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // JobVersionListResultIterator provides access to a complete listing of JobVersion values. type JobVersionListResultIterator struct { i int page JobVersionListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *JobVersionListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobVersionListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *JobVersionListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter JobVersionListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter JobVersionListResultIterator) Response() JobVersionListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter JobVersionListResultIterator) Value() JobVersion { if !iter.page.NotDone() { return JobVersion{} } return iter.page.Values()[iter.i] } // Creates a new instance of the JobVersionListResultIterator type. func NewJobVersionListResultIterator(page JobVersionListResultPage) JobVersionListResultIterator { return JobVersionListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (jvlr JobVersionListResult) IsEmpty() bool { return jvlr.Value == nil || len(*jvlr.Value) == 0 } // jobVersionListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (jvlr JobVersionListResult) jobVersionListResultPreparer(ctx context.Context) (*http.Request, error) { if jvlr.NextLink == nil || len(to.String(jvlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(jvlr.NextLink))) } // JobVersionListResultPage contains a page of JobVersion values. type JobVersionListResultPage struct { fn func(context.Context, JobVersionListResult) (JobVersionListResult, error) jvlr JobVersionListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *JobVersionListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/JobVersionListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.jvlr) if err != nil { return err } page.jvlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *JobVersionListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page JobVersionListResultPage) NotDone() bool { return !page.jvlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page JobVersionListResultPage) Response() JobVersionListResult { return page.jvlr } // Values returns the slice of values for the current page or nil if there are no values. func (page JobVersionListResultPage) Values() []JobVersion { if page.jvlr.IsEmpty() { return nil } return *page.jvlr.Value } // Creates a new instance of the JobVersionListResultPage type. func NewJobVersionListResultPage(getNextPage func(context.Context, JobVersionListResult) (JobVersionListResult, error)) JobVersionListResultPage { return JobVersionListResultPage{fn: getNextPage} } // LicenseTypeCapability the license type capability type LicenseTypeCapability struct { // Name - READ-ONLY; License type identifier. Name *string `json:"name,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // LocationCapabilities the location capability. type LocationCapabilities struct { autorest.Response `json:"-"` // Name - READ-ONLY; The location name. Name *string `json:"name,omitempty"` // SupportedServerVersions - READ-ONLY; The list of supported server versions. SupportedServerVersions *[]ServerVersionCapability `json:"supportedServerVersions,omitempty"` // SupportedManagedInstanceVersions - READ-ONLY; The list of supported managed instance versions. SupportedManagedInstanceVersions *[]ManagedInstanceVersionCapability `json:"supportedManagedInstanceVersions,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // LogicalServerSecurityAlertPolicyListResult a list of the server's security alert policies. type LogicalServerSecurityAlertPolicyListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ServerSecurityAlertPolicy `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // LogicalServerSecurityAlertPolicyListResultIterator provides access to a complete listing of // ServerSecurityAlertPolicy values. type LogicalServerSecurityAlertPolicyListResultIterator struct { i int page LogicalServerSecurityAlertPolicyListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *LogicalServerSecurityAlertPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/LogicalServerSecurityAlertPolicyListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *LogicalServerSecurityAlertPolicyListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter LogicalServerSecurityAlertPolicyListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter LogicalServerSecurityAlertPolicyListResultIterator) Response() LogicalServerSecurityAlertPolicyListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter LogicalServerSecurityAlertPolicyListResultIterator) Value() ServerSecurityAlertPolicy { if !iter.page.NotDone() { return ServerSecurityAlertPolicy{} } return iter.page.Values()[iter.i] } // Creates a new instance of the LogicalServerSecurityAlertPolicyListResultIterator type. func NewLogicalServerSecurityAlertPolicyListResultIterator(page LogicalServerSecurityAlertPolicyListResultPage) LogicalServerSecurityAlertPolicyListResultIterator { return LogicalServerSecurityAlertPolicyListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (lssaplr LogicalServerSecurityAlertPolicyListResult) IsEmpty() bool { return lssaplr.Value == nil || len(*lssaplr.Value) == 0 } // logicalServerSecurityAlertPolicyListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (lssaplr LogicalServerSecurityAlertPolicyListResult) logicalServerSecurityAlertPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { if lssaplr.NextLink == nil || len(to.String(lssaplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(lssaplr.NextLink))) } // LogicalServerSecurityAlertPolicyListResultPage contains a page of ServerSecurityAlertPolicy values. type LogicalServerSecurityAlertPolicyListResultPage struct { fn func(context.Context, LogicalServerSecurityAlertPolicyListResult) (LogicalServerSecurityAlertPolicyListResult, error) lssaplr LogicalServerSecurityAlertPolicyListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *LogicalServerSecurityAlertPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/LogicalServerSecurityAlertPolicyListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.lssaplr) if err != nil { return err } page.lssaplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *LogicalServerSecurityAlertPolicyListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page LogicalServerSecurityAlertPolicyListResultPage) NotDone() bool { return !page.lssaplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page LogicalServerSecurityAlertPolicyListResultPage) Response() LogicalServerSecurityAlertPolicyListResult { return page.lssaplr } // Values returns the slice of values for the current page or nil if there are no values. func (page LogicalServerSecurityAlertPolicyListResultPage) Values() []ServerSecurityAlertPolicy { if page.lssaplr.IsEmpty() { return nil } return *page.lssaplr.Value } // Creates a new instance of the LogicalServerSecurityAlertPolicyListResultPage type. func NewLogicalServerSecurityAlertPolicyListResultPage(getNextPage func(context.Context, LogicalServerSecurityAlertPolicyListResult) (LogicalServerSecurityAlertPolicyListResult, error)) LogicalServerSecurityAlertPolicyListResultPage { return LogicalServerSecurityAlertPolicyListResultPage{fn: getNextPage} } // LogSizeCapability the log size capability. type LogSizeCapability struct { // Limit - READ-ONLY; The log size limit (see 'unit' for the units). Limit *int32 `json:"limit,omitempty"` // Unit - READ-ONLY; The units that the limit is expressed in. Possible values include: 'Megabytes', 'Gigabytes', 'Terabytes', 'Petabytes', 'Percent' Unit LogSizeUnit `json:"unit,omitempty"` } // LongTermRetentionBackup a long term retention backup. type LongTermRetentionBackup struct { autorest.Response `json:"-"` // LongTermRetentionBackupProperties - Resource properties. *LongTermRetentionBackupProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for LongTermRetentionBackup. func (ltrb LongTermRetentionBackup) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if ltrb.LongTermRetentionBackupProperties != nil { objectMap["properties"] = ltrb.LongTermRetentionBackupProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for LongTermRetentionBackup struct. func (ltrb *LongTermRetentionBackup) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var longTermRetentionBackupProperties LongTermRetentionBackupProperties err = json.Unmarshal(*v, &longTermRetentionBackupProperties) if err != nil { return err } ltrb.LongTermRetentionBackupProperties = &longTermRetentionBackupProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } ltrb.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } ltrb.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } ltrb.Type = &typeVar } } } return nil } // LongTermRetentionBackupListResult a list of long term retention backups. type LongTermRetentionBackupListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]LongTermRetentionBackup `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // LongTermRetentionBackupListResultIterator provides access to a complete listing of // LongTermRetentionBackup values. type LongTermRetentionBackupListResultIterator struct { i int page LongTermRetentionBackupListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *LongTermRetentionBackupListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/LongTermRetentionBackupListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *LongTermRetentionBackupListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter LongTermRetentionBackupListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter LongTermRetentionBackupListResultIterator) Response() LongTermRetentionBackupListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter LongTermRetentionBackupListResultIterator) Value() LongTermRetentionBackup { if !iter.page.NotDone() { return LongTermRetentionBackup{} } return iter.page.Values()[iter.i] } // Creates a new instance of the LongTermRetentionBackupListResultIterator type. func NewLongTermRetentionBackupListResultIterator(page LongTermRetentionBackupListResultPage) LongTermRetentionBackupListResultIterator { return LongTermRetentionBackupListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (ltrblr LongTermRetentionBackupListResult) IsEmpty() bool { return ltrblr.Value == nil || len(*ltrblr.Value) == 0 } // longTermRetentionBackupListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (ltrblr LongTermRetentionBackupListResult) longTermRetentionBackupListResultPreparer(ctx context.Context) (*http.Request, error) { if ltrblr.NextLink == nil || len(to.String(ltrblr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(ltrblr.NextLink))) } // LongTermRetentionBackupListResultPage contains a page of LongTermRetentionBackup values. type LongTermRetentionBackupListResultPage struct { fn func(context.Context, LongTermRetentionBackupListResult) (LongTermRetentionBackupListResult, error) ltrblr LongTermRetentionBackupListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *LongTermRetentionBackupListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/LongTermRetentionBackupListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.ltrblr) if err != nil { return err } page.ltrblr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *LongTermRetentionBackupListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page LongTermRetentionBackupListResultPage) NotDone() bool { return !page.ltrblr.IsEmpty() } // Response returns the raw server response from the last page request. func (page LongTermRetentionBackupListResultPage) Response() LongTermRetentionBackupListResult { return page.ltrblr } // Values returns the slice of values for the current page or nil if there are no values. func (page LongTermRetentionBackupListResultPage) Values() []LongTermRetentionBackup { if page.ltrblr.IsEmpty() { return nil } return *page.ltrblr.Value } // Creates a new instance of the LongTermRetentionBackupListResultPage type. func NewLongTermRetentionBackupListResultPage(getNextPage func(context.Context, LongTermRetentionBackupListResult) (LongTermRetentionBackupListResult, error)) LongTermRetentionBackupListResultPage { return LongTermRetentionBackupListResultPage{fn: getNextPage} } // LongTermRetentionBackupProperties properties of a long term retention backup type LongTermRetentionBackupProperties struct { // ServerName - READ-ONLY; The server name that the backup database belong to. ServerName *string `json:"serverName,omitempty"` // ServerCreateTime - READ-ONLY; The create time of the server. ServerCreateTime *date.Time `json:"serverCreateTime,omitempty"` // DatabaseName - READ-ONLY; The name of the database the backup belong to DatabaseName *string `json:"databaseName,omitempty"` // DatabaseDeletionTime - READ-ONLY; The delete time of the database DatabaseDeletionTime *date.Time `json:"databaseDeletionTime,omitempty"` // BackupTime - READ-ONLY; The time the backup was taken BackupTime *date.Time `json:"backupTime,omitempty"` // BackupExpirationTime - READ-ONLY; The time the long term retention backup will expire. BackupExpirationTime *date.Time `json:"backupExpirationTime,omitempty"` } // LongTermRetentionBackupsDeleteByResourceGroupFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type LongTermRetentionBackupsDeleteByResourceGroupFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *LongTermRetentionBackupsDeleteByResourceGroupFuture) Result(client LongTermRetentionBackupsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.LongTermRetentionBackupsDeleteByResourceGroupFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.LongTermRetentionBackupsDeleteByResourceGroupFuture") return } ar.Response = future.Response() return } // LongTermRetentionBackupsDeleteFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type LongTermRetentionBackupsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *LongTermRetentionBackupsDeleteFuture) Result(client LongTermRetentionBackupsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.LongTermRetentionBackupsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.LongTermRetentionBackupsDeleteFuture") return } ar.Response = future.Response() return } // LongTermRetentionPolicyProperties properties of a long term retention policy type LongTermRetentionPolicyProperties struct { // WeeklyRetention - The weekly retention policy for an LTR backup in an ISO 8601 format. WeeklyRetention *string `json:"weeklyRetention,omitempty"` // MonthlyRetention - The monthly retention policy for an LTR backup in an ISO 8601 format. MonthlyRetention *string `json:"monthlyRetention,omitempty"` // YearlyRetention - The yearly retention policy for an LTR backup in an ISO 8601 format. YearlyRetention *string `json:"yearlyRetention,omitempty"` // WeekOfYear - The week of year to take the yearly backup in an ISO 8601 format. WeekOfYear *int32 `json:"weekOfYear,omitempty"` } // ManagedBackupShortTermRetentionPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving // the results of a long-running operation. type ManagedBackupShortTermRetentionPoliciesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedBackupShortTermRetentionPoliciesCreateOrUpdateFuture) Result(client ManagedBackupShortTermRetentionPoliciesClient) (mbstrp ManagedBackupShortTermRetentionPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedBackupShortTermRetentionPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedBackupShortTermRetentionPoliciesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if mbstrp.Response.Response, err = future.GetResult(sender); err == nil && mbstrp.Response.Response.StatusCode != http.StatusNoContent { mbstrp, err = client.CreateOrUpdateResponder(mbstrp.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedBackupShortTermRetentionPoliciesCreateOrUpdateFuture", "Result", mbstrp.Response.Response, "Failure responding to request") } } return } // ManagedBackupShortTermRetentionPoliciesUpdateFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type ManagedBackupShortTermRetentionPoliciesUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedBackupShortTermRetentionPoliciesUpdateFuture) Result(client ManagedBackupShortTermRetentionPoliciesClient) (mbstrp ManagedBackupShortTermRetentionPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedBackupShortTermRetentionPoliciesUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedBackupShortTermRetentionPoliciesUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if mbstrp.Response.Response, err = future.GetResult(sender); err == nil && mbstrp.Response.Response.StatusCode != http.StatusNoContent { mbstrp, err = client.UpdateResponder(mbstrp.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedBackupShortTermRetentionPoliciesUpdateFuture", "Result", mbstrp.Response.Response, "Failure responding to request") } } return } // ManagedBackupShortTermRetentionPolicy a short term retention policy. type ManagedBackupShortTermRetentionPolicy struct { autorest.Response `json:"-"` // ManagedBackupShortTermRetentionPolicyProperties - Resource properties. *ManagedBackupShortTermRetentionPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ManagedBackupShortTermRetentionPolicy. func (mbstrp ManagedBackupShortTermRetentionPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if mbstrp.ManagedBackupShortTermRetentionPolicyProperties != nil { objectMap["properties"] = mbstrp.ManagedBackupShortTermRetentionPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedBackupShortTermRetentionPolicy struct. func (mbstrp *ManagedBackupShortTermRetentionPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var managedBackupShortTermRetentionPolicyProperties ManagedBackupShortTermRetentionPolicyProperties err = json.Unmarshal(*v, &managedBackupShortTermRetentionPolicyProperties) if err != nil { return err } mbstrp.ManagedBackupShortTermRetentionPolicyProperties = &managedBackupShortTermRetentionPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } mbstrp.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } mbstrp.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } mbstrp.Type = &typeVar } } } return nil } // ManagedBackupShortTermRetentionPolicyListResult a list of short term retention policies. type ManagedBackupShortTermRetentionPolicyListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ManagedBackupShortTermRetentionPolicy `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ManagedBackupShortTermRetentionPolicyListResultIterator provides access to a complete listing of // ManagedBackupShortTermRetentionPolicy values. type ManagedBackupShortTermRetentionPolicyListResultIterator struct { i int page ManagedBackupShortTermRetentionPolicyListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ManagedBackupShortTermRetentionPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedBackupShortTermRetentionPolicyListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ManagedBackupShortTermRetentionPolicyListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ManagedBackupShortTermRetentionPolicyListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ManagedBackupShortTermRetentionPolicyListResultIterator) Response() ManagedBackupShortTermRetentionPolicyListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ManagedBackupShortTermRetentionPolicyListResultIterator) Value() ManagedBackupShortTermRetentionPolicy { if !iter.page.NotDone() { return ManagedBackupShortTermRetentionPolicy{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ManagedBackupShortTermRetentionPolicyListResultIterator type. func NewManagedBackupShortTermRetentionPolicyListResultIterator(page ManagedBackupShortTermRetentionPolicyListResultPage) ManagedBackupShortTermRetentionPolicyListResultIterator { return ManagedBackupShortTermRetentionPolicyListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (mbstrplr ManagedBackupShortTermRetentionPolicyListResult) IsEmpty() bool { return mbstrplr.Value == nil || len(*mbstrplr.Value) == 0 } // managedBackupShortTermRetentionPolicyListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (mbstrplr ManagedBackupShortTermRetentionPolicyListResult) managedBackupShortTermRetentionPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { if mbstrplr.NextLink == nil || len(to.String(mbstrplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(mbstrplr.NextLink))) } // ManagedBackupShortTermRetentionPolicyListResultPage contains a page of // ManagedBackupShortTermRetentionPolicy values. type ManagedBackupShortTermRetentionPolicyListResultPage struct { fn func(context.Context, ManagedBackupShortTermRetentionPolicyListResult) (ManagedBackupShortTermRetentionPolicyListResult, error) mbstrplr ManagedBackupShortTermRetentionPolicyListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ManagedBackupShortTermRetentionPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedBackupShortTermRetentionPolicyListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.mbstrplr) if err != nil { return err } page.mbstrplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ManagedBackupShortTermRetentionPolicyListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ManagedBackupShortTermRetentionPolicyListResultPage) NotDone() bool { return !page.mbstrplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ManagedBackupShortTermRetentionPolicyListResultPage) Response() ManagedBackupShortTermRetentionPolicyListResult { return page.mbstrplr } // Values returns the slice of values for the current page or nil if there are no values. func (page ManagedBackupShortTermRetentionPolicyListResultPage) Values() []ManagedBackupShortTermRetentionPolicy { if page.mbstrplr.IsEmpty() { return nil } return *page.mbstrplr.Value } // Creates a new instance of the ManagedBackupShortTermRetentionPolicyListResultPage type. func NewManagedBackupShortTermRetentionPolicyListResultPage(getNextPage func(context.Context, ManagedBackupShortTermRetentionPolicyListResult) (ManagedBackupShortTermRetentionPolicyListResult, error)) ManagedBackupShortTermRetentionPolicyListResultPage { return ManagedBackupShortTermRetentionPolicyListResultPage{fn: getNextPage} } // ManagedBackupShortTermRetentionPolicyProperties properties of a short term retention policy type ManagedBackupShortTermRetentionPolicyProperties struct { // RetentionDays - The backup retention period in days. This is how many days Point-in-Time Restore will be supported. RetentionDays *int32 `json:"retentionDays,omitempty"` } // ManagedDatabase a managed database resource. type ManagedDatabase struct { autorest.Response `json:"-"` // ManagedDatabaseProperties - Resource properties. *ManagedDatabaseProperties `json:"properties,omitempty"` // Location - Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ManagedDatabase. func (md ManagedDatabase) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if md.ManagedDatabaseProperties != nil { objectMap["properties"] = md.ManagedDatabaseProperties } if md.Location != nil { objectMap["location"] = md.Location } if md.Tags != nil { objectMap["tags"] = md.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedDatabase struct. func (md *ManagedDatabase) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var managedDatabaseProperties ManagedDatabaseProperties err = json.Unmarshal(*v, &managedDatabaseProperties) if err != nil { return err } md.ManagedDatabaseProperties = &managedDatabaseProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } md.Location = &location } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } md.Tags = tags } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } md.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } md.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } md.Type = &typeVar } } } return nil } // ManagedDatabaseListResult a list of managed databases. type ManagedDatabaseListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ManagedDatabase `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ManagedDatabaseListResultIterator provides access to a complete listing of ManagedDatabase values. type ManagedDatabaseListResultIterator struct { i int page ManagedDatabaseListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ManagedDatabaseListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedDatabaseListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ManagedDatabaseListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ManagedDatabaseListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ManagedDatabaseListResultIterator) Response() ManagedDatabaseListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ManagedDatabaseListResultIterator) Value() ManagedDatabase { if !iter.page.NotDone() { return ManagedDatabase{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ManagedDatabaseListResultIterator type. func NewManagedDatabaseListResultIterator(page ManagedDatabaseListResultPage) ManagedDatabaseListResultIterator { return ManagedDatabaseListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (mdlr ManagedDatabaseListResult) IsEmpty() bool { return mdlr.Value == nil || len(*mdlr.Value) == 0 } // managedDatabaseListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (mdlr ManagedDatabaseListResult) managedDatabaseListResultPreparer(ctx context.Context) (*http.Request, error) { if mdlr.NextLink == nil || len(to.String(mdlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(mdlr.NextLink))) } // ManagedDatabaseListResultPage contains a page of ManagedDatabase values. type ManagedDatabaseListResultPage struct { fn func(context.Context, ManagedDatabaseListResult) (ManagedDatabaseListResult, error) mdlr ManagedDatabaseListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ManagedDatabaseListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedDatabaseListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.mdlr) if err != nil { return err } page.mdlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ManagedDatabaseListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ManagedDatabaseListResultPage) NotDone() bool { return !page.mdlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ManagedDatabaseListResultPage) Response() ManagedDatabaseListResult { return page.mdlr } // Values returns the slice of values for the current page or nil if there are no values. func (page ManagedDatabaseListResultPage) Values() []ManagedDatabase { if page.mdlr.IsEmpty() { return nil } return *page.mdlr.Value } // Creates a new instance of the ManagedDatabaseListResultPage type. func NewManagedDatabaseListResultPage(getNextPage func(context.Context, ManagedDatabaseListResult) (ManagedDatabaseListResult, error)) ManagedDatabaseListResultPage { return ManagedDatabaseListResultPage{fn: getNextPage} } // ManagedDatabaseProperties the managed database's properties. type ManagedDatabaseProperties struct { // Collation - Collation of the managed database. Collation *string `json:"collation,omitempty"` // Status - READ-ONLY; Status of the database. Possible values include: 'Online', 'Offline', 'Shutdown', 'Creating', 'Inaccessible', 'Restoring', 'Updating' Status ManagedDatabaseStatus `json:"status,omitempty"` // CreationDate - READ-ONLY; Creation date of the database. CreationDate *date.Time `json:"creationDate,omitempty"` // EarliestRestorePoint - READ-ONLY; Earliest restore point in time for point in time restore. EarliestRestorePoint *date.Time `json:"earliestRestorePoint,omitempty"` // RestorePointInTime - Conditional. If createMode is PointInTimeRestore, this value is required. Specifies the point in time (ISO8601 format) of the source database that will be restored to create the new database. RestorePointInTime *date.Time `json:"restorePointInTime,omitempty"` // DefaultSecondaryLocation - READ-ONLY; Geo paired region. DefaultSecondaryLocation *string `json:"defaultSecondaryLocation,omitempty"` // CatalogCollation - Collation of the metadata catalog. Possible values include: 'DATABASEDEFAULT', 'SQLLatin1GeneralCP1CIAS' CatalogCollation CatalogCollationType `json:"catalogCollation,omitempty"` // CreateMode - Managed database create mode. PointInTimeRestore: Create a database by restoring a point in time backup of an existing database. SourceDatabaseName, SourceManagedInstanceName and PointInTime must be specified. RestoreExternalBackup: Create a database by restoring from external backup files. Collation, StorageContainerUri and StorageContainerSasToken must be specified. Recovery: Creates a database by restoring a geo-replicated backup. RecoverableDatabaseId must be specified as the recoverable database resource ID to restore. Possible values include: 'ManagedDatabaseCreateModeDefault', 'ManagedDatabaseCreateModeRestoreExternalBackup', 'ManagedDatabaseCreateModePointInTimeRestore', 'ManagedDatabaseCreateModeRecovery' CreateMode ManagedDatabaseCreateMode `json:"createMode,omitempty"` // StorageContainerURI - Conditional. If createMode is RestoreExternalBackup, this value is required. Specifies the uri of the storage container where backups for this restore are stored. StorageContainerURI *string `json:"storageContainerUri,omitempty"` // SourceDatabaseID - The resource identifier of the source database associated with create operation of this database. SourceDatabaseID *string `json:"sourceDatabaseId,omitempty"` // RestorableDroppedDatabaseID - The restorable dropped database resource id to restore when creating this database. RestorableDroppedDatabaseID *string `json:"restorableDroppedDatabaseId,omitempty"` // StorageContainerSasToken - Conditional. If createMode is RestoreExternalBackup, this value is required. Specifies the storage container sas token. StorageContainerSasToken *string `json:"storageContainerSasToken,omitempty"` // FailoverGroupID - READ-ONLY; Instance Failover Group resource identifier that this managed database belongs to. FailoverGroupID *string `json:"failoverGroupId,omitempty"` // RecoverableDatabaseID - The resource identifier of the recoverable database associated with create operation of this database. RecoverableDatabaseID *string `json:"recoverableDatabaseId,omitempty"` } // ManagedDatabaseRestoreDetailsProperties the managed database's restore details properties. type ManagedDatabaseRestoreDetailsProperties struct { // Status - READ-ONLY; Restore status. Status *string `json:"status,omitempty"` // CurrentRestoringFileName - READ-ONLY; Current restoring file name. CurrentRestoringFileName *string `json:"currentRestoringFileName,omitempty"` // LastRestoredFileName - READ-ONLY; Last restored file name. LastRestoredFileName *string `json:"lastRestoredFileName,omitempty"` // LastRestoredFileTime - READ-ONLY; Last restored file time. LastRestoredFileTime *date.Time `json:"lastRestoredFileTime,omitempty"` // PercentCompleted - READ-ONLY; Percent completed. PercentCompleted *float64 `json:"percentCompleted,omitempty"` // UnrestorableFiles - READ-ONLY; List of unrestorable files. UnrestorableFiles *[]string `json:"unrestorableFiles,omitempty"` // NumberOfFilesDetected - READ-ONLY; Number of files detected. NumberOfFilesDetected *int64 `json:"numberOfFilesDetected,omitempty"` // LastUploadedFileName - READ-ONLY; Last uploaded file name. LastUploadedFileName *string `json:"lastUploadedFileName,omitempty"` // LastUploadedFileTime - READ-ONLY; Last uploaded file time. LastUploadedFileTime *date.Time `json:"lastUploadedFileTime,omitempty"` // BlockReason - READ-ONLY; The reason why restore is in Blocked state. BlockReason *string `json:"blockReason,omitempty"` } // ManagedDatabaseRestoreDetailsResult a managed database restore details. type ManagedDatabaseRestoreDetailsResult struct { autorest.Response `json:"-"` // ManagedDatabaseRestoreDetailsProperties - Resource properties. *ManagedDatabaseRestoreDetailsProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ManagedDatabaseRestoreDetailsResult. func (mdrdr ManagedDatabaseRestoreDetailsResult) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if mdrdr.ManagedDatabaseRestoreDetailsProperties != nil { objectMap["properties"] = mdrdr.ManagedDatabaseRestoreDetailsProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedDatabaseRestoreDetailsResult struct. func (mdrdr *ManagedDatabaseRestoreDetailsResult) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var managedDatabaseRestoreDetailsProperties ManagedDatabaseRestoreDetailsProperties err = json.Unmarshal(*v, &managedDatabaseRestoreDetailsProperties) if err != nil { return err } mdrdr.ManagedDatabaseRestoreDetailsProperties = &managedDatabaseRestoreDetailsProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } mdrdr.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } mdrdr.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } mdrdr.Type = &typeVar } } } return nil } // ManagedDatabasesCompleteRestoreFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ManagedDatabasesCompleteRestoreFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedDatabasesCompleteRestoreFuture) Result(client ManagedDatabasesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedDatabasesCompleteRestoreFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedDatabasesCompleteRestoreFuture") return } ar.Response = future.Response() return } // ManagedDatabasesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ManagedDatabasesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedDatabasesCreateOrUpdateFuture) Result(client ManagedDatabasesClient) (md ManagedDatabase, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedDatabasesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedDatabasesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if md.Response.Response, err = future.GetResult(sender); err == nil && md.Response.Response.StatusCode != http.StatusNoContent { md, err = client.CreateOrUpdateResponder(md.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedDatabasesCreateOrUpdateFuture", "Result", md.Response.Response, "Failure responding to request") } } return } // ManagedDatabasesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ManagedDatabasesDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedDatabasesDeleteFuture) Result(client ManagedDatabasesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedDatabasesDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedDatabasesDeleteFuture") return } ar.Response = future.Response() return } // ManagedDatabaseSecurityAlertPolicy a managed database security alert policy. type ManagedDatabaseSecurityAlertPolicy struct { autorest.Response `json:"-"` // SecurityAlertPolicyProperties - Resource properties. *SecurityAlertPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ManagedDatabaseSecurityAlertPolicy. func (mdsap ManagedDatabaseSecurityAlertPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if mdsap.SecurityAlertPolicyProperties != nil { objectMap["properties"] = mdsap.SecurityAlertPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedDatabaseSecurityAlertPolicy struct. func (mdsap *ManagedDatabaseSecurityAlertPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var securityAlertPolicyProperties SecurityAlertPolicyProperties err = json.Unmarshal(*v, &securityAlertPolicyProperties) if err != nil { return err } mdsap.SecurityAlertPolicyProperties = &securityAlertPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } mdsap.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } mdsap.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } mdsap.Type = &typeVar } } } return nil } // ManagedDatabaseSecurityAlertPolicyListResult a list of the managed database's security alert policies. type ManagedDatabaseSecurityAlertPolicyListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ManagedDatabaseSecurityAlertPolicy `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ManagedDatabaseSecurityAlertPolicyListResultIterator provides access to a complete listing of // ManagedDatabaseSecurityAlertPolicy values. type ManagedDatabaseSecurityAlertPolicyListResultIterator struct { i int page ManagedDatabaseSecurityAlertPolicyListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ManagedDatabaseSecurityAlertPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedDatabaseSecurityAlertPolicyListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ManagedDatabaseSecurityAlertPolicyListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ManagedDatabaseSecurityAlertPolicyListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ManagedDatabaseSecurityAlertPolicyListResultIterator) Response() ManagedDatabaseSecurityAlertPolicyListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ManagedDatabaseSecurityAlertPolicyListResultIterator) Value() ManagedDatabaseSecurityAlertPolicy { if !iter.page.NotDone() { return ManagedDatabaseSecurityAlertPolicy{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ManagedDatabaseSecurityAlertPolicyListResultIterator type. func NewManagedDatabaseSecurityAlertPolicyListResultIterator(page ManagedDatabaseSecurityAlertPolicyListResultPage) ManagedDatabaseSecurityAlertPolicyListResultIterator { return ManagedDatabaseSecurityAlertPolicyListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (mdsaplr ManagedDatabaseSecurityAlertPolicyListResult) IsEmpty() bool { return mdsaplr.Value == nil || len(*mdsaplr.Value) == 0 } // managedDatabaseSecurityAlertPolicyListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (mdsaplr ManagedDatabaseSecurityAlertPolicyListResult) managedDatabaseSecurityAlertPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { if mdsaplr.NextLink == nil || len(to.String(mdsaplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(mdsaplr.NextLink))) } // ManagedDatabaseSecurityAlertPolicyListResultPage contains a page of ManagedDatabaseSecurityAlertPolicy // values. type ManagedDatabaseSecurityAlertPolicyListResultPage struct { fn func(context.Context, ManagedDatabaseSecurityAlertPolicyListResult) (ManagedDatabaseSecurityAlertPolicyListResult, error) mdsaplr ManagedDatabaseSecurityAlertPolicyListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ManagedDatabaseSecurityAlertPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedDatabaseSecurityAlertPolicyListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.mdsaplr) if err != nil { return err } page.mdsaplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ManagedDatabaseSecurityAlertPolicyListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ManagedDatabaseSecurityAlertPolicyListResultPage) NotDone() bool { return !page.mdsaplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ManagedDatabaseSecurityAlertPolicyListResultPage) Response() ManagedDatabaseSecurityAlertPolicyListResult { return page.mdsaplr } // Values returns the slice of values for the current page or nil if there are no values. func (page ManagedDatabaseSecurityAlertPolicyListResultPage) Values() []ManagedDatabaseSecurityAlertPolicy { if page.mdsaplr.IsEmpty() { return nil } return *page.mdsaplr.Value } // Creates a new instance of the ManagedDatabaseSecurityAlertPolicyListResultPage type. func NewManagedDatabaseSecurityAlertPolicyListResultPage(getNextPage func(context.Context, ManagedDatabaseSecurityAlertPolicyListResult) (ManagedDatabaseSecurityAlertPolicyListResult, error)) ManagedDatabaseSecurityAlertPolicyListResultPage { return ManagedDatabaseSecurityAlertPolicyListResultPage{fn: getNextPage} } // ManagedDatabasesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ManagedDatabasesUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedDatabasesUpdateFuture) Result(client ManagedDatabasesClient) (md ManagedDatabase, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedDatabasesUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedDatabasesUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if md.Response.Response, err = future.GetResult(sender); err == nil && md.Response.Response.StatusCode != http.StatusNoContent { md, err = client.UpdateResponder(md.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedDatabasesUpdateFuture", "Result", md.Response.Response, "Failure responding to request") } } return } // ManagedDatabaseUpdate an managed database update. type ManagedDatabaseUpdate struct { // ManagedDatabaseProperties - Resource properties. *ManagedDatabaseProperties `json:"properties,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` } // MarshalJSON is the custom marshaler for ManagedDatabaseUpdate. func (mdu ManagedDatabaseUpdate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if mdu.ManagedDatabaseProperties != nil { objectMap["properties"] = mdu.ManagedDatabaseProperties } if mdu.Tags != nil { objectMap["tags"] = mdu.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedDatabaseUpdate struct. func (mdu *ManagedDatabaseUpdate) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var managedDatabaseProperties ManagedDatabaseProperties err = json.Unmarshal(*v, &managedDatabaseProperties) if err != nil { return err } mdu.ManagedDatabaseProperties = &managedDatabaseProperties } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } mdu.Tags = tags } } } return nil } // ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture an abstraction for monitoring and // retrieving the results of a long-running operation. type ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture) Result(client ManagedDatabaseVulnerabilityAssessmentScansClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedDatabaseVulnerabilityAssessmentScansInitiateScanFuture") return } ar.Response = future.Response() return } // ManagedInstance an Azure SQL managed instance. type ManagedInstance struct { autorest.Response `json:"-"` // Identity - The Azure Active Directory identity of the managed instance. Identity *ResourceIdentity `json:"identity,omitempty"` // Sku - Managed instance SKU. Allowed values for sku.name: GP_Gen4, GP_Gen5, BC_Gen4, BC_Gen5 Sku *Sku `json:"sku,omitempty"` // ManagedInstanceProperties - Resource properties. *ManagedInstanceProperties `json:"properties,omitempty"` // Location - Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ManagedInstance. func (mi ManagedInstance) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if mi.Identity != nil { objectMap["identity"] = mi.Identity } if mi.Sku != nil { objectMap["sku"] = mi.Sku } if mi.ManagedInstanceProperties != nil { objectMap["properties"] = mi.ManagedInstanceProperties } if mi.Location != nil { objectMap["location"] = mi.Location } if mi.Tags != nil { objectMap["tags"] = mi.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedInstance struct. func (mi *ManagedInstance) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "identity": if v != nil { var identity ResourceIdentity err = json.Unmarshal(*v, &identity) if err != nil { return err } mi.Identity = &identity } case "sku": if v != nil { var sku Sku err = json.Unmarshal(*v, &sku) if err != nil { return err } mi.Sku = &sku } case "properties": if v != nil { var managedInstanceProperties ManagedInstanceProperties err = json.Unmarshal(*v, &managedInstanceProperties) if err != nil { return err } mi.ManagedInstanceProperties = &managedInstanceProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } mi.Location = &location } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } mi.Tags = tags } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } mi.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } mi.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } mi.Type = &typeVar } } } return nil } // ManagedInstanceAdministrator an Azure SQL managed instance administrator. type ManagedInstanceAdministrator struct { autorest.Response `json:"-"` // ManagedInstanceAdministratorProperties - Resource properties. *ManagedInstanceAdministratorProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ManagedInstanceAdministrator. func (mia ManagedInstanceAdministrator) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if mia.ManagedInstanceAdministratorProperties != nil { objectMap["properties"] = mia.ManagedInstanceAdministratorProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedInstanceAdministrator struct. func (mia *ManagedInstanceAdministrator) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var managedInstanceAdministratorProperties ManagedInstanceAdministratorProperties err = json.Unmarshal(*v, &managedInstanceAdministratorProperties) if err != nil { return err } mia.ManagedInstanceAdministratorProperties = &managedInstanceAdministratorProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } mia.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } mia.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } mia.Type = &typeVar } } } return nil } // ManagedInstanceAdministratorListResult a list of managed instance administrators. type ManagedInstanceAdministratorListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ManagedInstanceAdministrator `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ManagedInstanceAdministratorListResultIterator provides access to a complete listing of // ManagedInstanceAdministrator values. type ManagedInstanceAdministratorListResultIterator struct { i int page ManagedInstanceAdministratorListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ManagedInstanceAdministratorListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedInstanceAdministratorListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ManagedInstanceAdministratorListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ManagedInstanceAdministratorListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ManagedInstanceAdministratorListResultIterator) Response() ManagedInstanceAdministratorListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ManagedInstanceAdministratorListResultIterator) Value() ManagedInstanceAdministrator { if !iter.page.NotDone() { return ManagedInstanceAdministrator{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ManagedInstanceAdministratorListResultIterator type. func NewManagedInstanceAdministratorListResultIterator(page ManagedInstanceAdministratorListResultPage) ManagedInstanceAdministratorListResultIterator { return ManagedInstanceAdministratorListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (mialr ManagedInstanceAdministratorListResult) IsEmpty() bool { return mialr.Value == nil || len(*mialr.Value) == 0 } // managedInstanceAdministratorListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (mialr ManagedInstanceAdministratorListResult) managedInstanceAdministratorListResultPreparer(ctx context.Context) (*http.Request, error) { if mialr.NextLink == nil || len(to.String(mialr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(mialr.NextLink))) } // ManagedInstanceAdministratorListResultPage contains a page of ManagedInstanceAdministrator values. type ManagedInstanceAdministratorListResultPage struct { fn func(context.Context, ManagedInstanceAdministratorListResult) (ManagedInstanceAdministratorListResult, error) mialr ManagedInstanceAdministratorListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ManagedInstanceAdministratorListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedInstanceAdministratorListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.mialr) if err != nil { return err } page.mialr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ManagedInstanceAdministratorListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ManagedInstanceAdministratorListResultPage) NotDone() bool { return !page.mialr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ManagedInstanceAdministratorListResultPage) Response() ManagedInstanceAdministratorListResult { return page.mialr } // Values returns the slice of values for the current page or nil if there are no values. func (page ManagedInstanceAdministratorListResultPage) Values() []ManagedInstanceAdministrator { if page.mialr.IsEmpty() { return nil } return *page.mialr.Value } // Creates a new instance of the ManagedInstanceAdministratorListResultPage type. func NewManagedInstanceAdministratorListResultPage(getNextPage func(context.Context, ManagedInstanceAdministratorListResult) (ManagedInstanceAdministratorListResult, error)) ManagedInstanceAdministratorListResultPage { return ManagedInstanceAdministratorListResultPage{fn: getNextPage} } // ManagedInstanceAdministratorProperties the properties of a managed instance administrator. type ManagedInstanceAdministratorProperties struct { // AdministratorType - Type of the managed instance administrator. AdministratorType *string `json:"administratorType,omitempty"` // Login - Login name of the managed instance administrator. Login *string `json:"login,omitempty"` // Sid - SID (object ID) of the managed instance administrator. Sid *uuid.UUID `json:"sid,omitempty"` // TenantID - Tenant ID of the managed instance administrator. TenantID *uuid.UUID `json:"tenantId,omitempty"` } // ManagedInstanceAdministratorsCreateOrUpdateFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type ManagedInstanceAdministratorsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedInstanceAdministratorsCreateOrUpdateFuture) Result(client ManagedInstanceAdministratorsClient) (mia ManagedInstanceAdministrator, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstanceAdministratorsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceAdministratorsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if mia.Response.Response, err = future.GetResult(sender); err == nil && mia.Response.Response.StatusCode != http.StatusNoContent { mia, err = client.CreateOrUpdateResponder(mia.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstanceAdministratorsCreateOrUpdateFuture", "Result", mia.Response.Response, "Failure responding to request") } } return } // ManagedInstanceAdministratorsDeleteFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ManagedInstanceAdministratorsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedInstanceAdministratorsDeleteFuture) Result(client ManagedInstanceAdministratorsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstanceAdministratorsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceAdministratorsDeleteFuture") return } ar.Response = future.Response() return } // ManagedInstanceEditionCapability the managed server capability type ManagedInstanceEditionCapability struct { // Name - READ-ONLY; The managed server version name. Name *string `json:"name,omitempty"` // SupportedFamilies - READ-ONLY; The supported families. SupportedFamilies *[]ManagedInstanceFamilyCapability `json:"supportedFamilies,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ManagedInstanceEncryptionProtector the managed instance encryption protector. type ManagedInstanceEncryptionProtector struct { autorest.Response `json:"-"` // Kind - READ-ONLY; Kind of encryption protector. This is metadata used for the Azure portal experience. Kind *string `json:"kind,omitempty"` // ManagedInstanceEncryptionProtectorProperties - Resource properties. *ManagedInstanceEncryptionProtectorProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ManagedInstanceEncryptionProtector. func (miep ManagedInstanceEncryptionProtector) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if miep.ManagedInstanceEncryptionProtectorProperties != nil { objectMap["properties"] = miep.ManagedInstanceEncryptionProtectorProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedInstanceEncryptionProtector struct. func (miep *ManagedInstanceEncryptionProtector) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } miep.Kind = &kind } case "properties": if v != nil { var managedInstanceEncryptionProtectorProperties ManagedInstanceEncryptionProtectorProperties err = json.Unmarshal(*v, &managedInstanceEncryptionProtectorProperties) if err != nil { return err } miep.ManagedInstanceEncryptionProtectorProperties = &managedInstanceEncryptionProtectorProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } miep.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } miep.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } miep.Type = &typeVar } } } return nil } // ManagedInstanceEncryptionProtectorListResult a list of managed instance encryption protectors. type ManagedInstanceEncryptionProtectorListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ManagedInstanceEncryptionProtector `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ManagedInstanceEncryptionProtectorListResultIterator provides access to a complete listing of // ManagedInstanceEncryptionProtector values. type ManagedInstanceEncryptionProtectorListResultIterator struct { i int page ManagedInstanceEncryptionProtectorListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ManagedInstanceEncryptionProtectorListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedInstanceEncryptionProtectorListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ManagedInstanceEncryptionProtectorListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ManagedInstanceEncryptionProtectorListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ManagedInstanceEncryptionProtectorListResultIterator) Response() ManagedInstanceEncryptionProtectorListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ManagedInstanceEncryptionProtectorListResultIterator) Value() ManagedInstanceEncryptionProtector { if !iter.page.NotDone() { return ManagedInstanceEncryptionProtector{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ManagedInstanceEncryptionProtectorListResultIterator type. func NewManagedInstanceEncryptionProtectorListResultIterator(page ManagedInstanceEncryptionProtectorListResultPage) ManagedInstanceEncryptionProtectorListResultIterator { return ManagedInstanceEncryptionProtectorListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (mieplr ManagedInstanceEncryptionProtectorListResult) IsEmpty() bool { return mieplr.Value == nil || len(*mieplr.Value) == 0 } // managedInstanceEncryptionProtectorListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (mieplr ManagedInstanceEncryptionProtectorListResult) managedInstanceEncryptionProtectorListResultPreparer(ctx context.Context) (*http.Request, error) { if mieplr.NextLink == nil || len(to.String(mieplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(mieplr.NextLink))) } // ManagedInstanceEncryptionProtectorListResultPage contains a page of ManagedInstanceEncryptionProtector // values. type ManagedInstanceEncryptionProtectorListResultPage struct { fn func(context.Context, ManagedInstanceEncryptionProtectorListResult) (ManagedInstanceEncryptionProtectorListResult, error) mieplr ManagedInstanceEncryptionProtectorListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ManagedInstanceEncryptionProtectorListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedInstanceEncryptionProtectorListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.mieplr) if err != nil { return err } page.mieplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ManagedInstanceEncryptionProtectorListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ManagedInstanceEncryptionProtectorListResultPage) NotDone() bool { return !page.mieplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ManagedInstanceEncryptionProtectorListResultPage) Response() ManagedInstanceEncryptionProtectorListResult { return page.mieplr } // Values returns the slice of values for the current page or nil if there are no values. func (page ManagedInstanceEncryptionProtectorListResultPage) Values() []ManagedInstanceEncryptionProtector { if page.mieplr.IsEmpty() { return nil } return *page.mieplr.Value } // Creates a new instance of the ManagedInstanceEncryptionProtectorListResultPage type. func NewManagedInstanceEncryptionProtectorListResultPage(getNextPage func(context.Context, ManagedInstanceEncryptionProtectorListResult) (ManagedInstanceEncryptionProtectorListResult, error)) ManagedInstanceEncryptionProtectorListResultPage { return ManagedInstanceEncryptionProtectorListResultPage{fn: getNextPage} } // ManagedInstanceEncryptionProtectorProperties properties for an encryption protector execution. type ManagedInstanceEncryptionProtectorProperties struct { // ServerKeyName - The name of the managed instance key. ServerKeyName *string `json:"serverKeyName,omitempty"` // ServerKeyType - The encryption protector type like 'ServiceManaged', 'AzureKeyVault'. Possible values include: 'ServiceManaged', 'AzureKeyVault' ServerKeyType ServerKeyType `json:"serverKeyType,omitempty"` // URI - READ-ONLY; The URI of the server key. URI *string `json:"uri,omitempty"` // Thumbprint - READ-ONLY; Thumbprint of the server key. Thumbprint *string `json:"thumbprint,omitempty"` } // ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture) Result(client ManagedInstanceEncryptionProtectorsClient) (miep ManagedInstanceEncryptionProtector, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if miep.Response.Response, err = future.GetResult(sender); err == nil && miep.Response.Response.StatusCode != http.StatusNoContent { miep, err = client.CreateOrUpdateResponder(miep.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsCreateOrUpdateFuture", "Result", miep.Response.Response, "Failure responding to request") } } return } // ManagedInstanceEncryptionProtectorsRevalidateFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type ManagedInstanceEncryptionProtectorsRevalidateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedInstanceEncryptionProtectorsRevalidateFuture) Result(client ManagedInstanceEncryptionProtectorsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstanceEncryptionProtectorsRevalidateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceEncryptionProtectorsRevalidateFuture") return } ar.Response = future.Response() return } // ManagedInstanceFamilyCapability the managed server family capability. type ManagedInstanceFamilyCapability struct { // Name - READ-ONLY; Family name. Name *string `json:"name,omitempty"` // Sku - READ-ONLY; SKU name. Sku *string `json:"sku,omitempty"` // SupportedLicenseTypes - READ-ONLY; List of supported license types. SupportedLicenseTypes *[]LicenseTypeCapability `json:"supportedLicenseTypes,omitempty"` // SupportedVcoresValues - READ-ONLY; List of supported virtual cores values. SupportedVcoresValues *[]ManagedInstanceVcoresCapability `json:"supportedVcoresValues,omitempty"` // IncludedMaxSize - READ-ONLY; Included size. IncludedMaxSize *MaxSizeCapability `json:"includedMaxSize,omitempty"` // SupportedStorageSizes - READ-ONLY; Storage size ranges. SupportedStorageSizes *[]MaxSizeRangeCapability `json:"supportedStorageSizes,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ManagedInstanceKey a managed instance key. type ManagedInstanceKey struct { autorest.Response `json:"-"` // Kind - READ-ONLY; Kind of encryption protector. This is metadata used for the Azure portal experience. Kind *string `json:"kind,omitempty"` // ManagedInstanceKeyProperties - Resource properties. *ManagedInstanceKeyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ManagedInstanceKey. func (mik ManagedInstanceKey) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if mik.ManagedInstanceKeyProperties != nil { objectMap["properties"] = mik.ManagedInstanceKeyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedInstanceKey struct. func (mik *ManagedInstanceKey) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } mik.Kind = &kind } case "properties": if v != nil { var managedInstanceKeyProperties ManagedInstanceKeyProperties err = json.Unmarshal(*v, &managedInstanceKeyProperties) if err != nil { return err } mik.ManagedInstanceKeyProperties = &managedInstanceKeyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } mik.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } mik.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } mik.Type = &typeVar } } } return nil } // ManagedInstanceKeyListResult a list of managed instance keys. type ManagedInstanceKeyListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ManagedInstanceKey `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ManagedInstanceKeyListResultIterator provides access to a complete listing of ManagedInstanceKey values. type ManagedInstanceKeyListResultIterator struct { i int page ManagedInstanceKeyListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ManagedInstanceKeyListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedInstanceKeyListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ManagedInstanceKeyListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ManagedInstanceKeyListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ManagedInstanceKeyListResultIterator) Response() ManagedInstanceKeyListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ManagedInstanceKeyListResultIterator) Value() ManagedInstanceKey { if !iter.page.NotDone() { return ManagedInstanceKey{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ManagedInstanceKeyListResultIterator type. func NewManagedInstanceKeyListResultIterator(page ManagedInstanceKeyListResultPage) ManagedInstanceKeyListResultIterator { return ManagedInstanceKeyListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (miklr ManagedInstanceKeyListResult) IsEmpty() bool { return miklr.Value == nil || len(*miklr.Value) == 0 } // managedInstanceKeyListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (miklr ManagedInstanceKeyListResult) managedInstanceKeyListResultPreparer(ctx context.Context) (*http.Request, error) { if miklr.NextLink == nil || len(to.String(miklr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(miklr.NextLink))) } // ManagedInstanceKeyListResultPage contains a page of ManagedInstanceKey values. type ManagedInstanceKeyListResultPage struct { fn func(context.Context, ManagedInstanceKeyListResult) (ManagedInstanceKeyListResult, error) miklr ManagedInstanceKeyListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ManagedInstanceKeyListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedInstanceKeyListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.miklr) if err != nil { return err } page.miklr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ManagedInstanceKeyListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ManagedInstanceKeyListResultPage) NotDone() bool { return !page.miklr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ManagedInstanceKeyListResultPage) Response() ManagedInstanceKeyListResult { return page.miklr } // Values returns the slice of values for the current page or nil if there are no values. func (page ManagedInstanceKeyListResultPage) Values() []ManagedInstanceKey { if page.miklr.IsEmpty() { return nil } return *page.miklr.Value } // Creates a new instance of the ManagedInstanceKeyListResultPage type. func NewManagedInstanceKeyListResultPage(getNextPage func(context.Context, ManagedInstanceKeyListResult) (ManagedInstanceKeyListResult, error)) ManagedInstanceKeyListResultPage { return ManagedInstanceKeyListResultPage{fn: getNextPage} } // ManagedInstanceKeyProperties properties for a key execution. type ManagedInstanceKeyProperties struct { // ServerKeyType - The key type like 'ServiceManaged', 'AzureKeyVault'. Possible values include: 'ServiceManaged', 'AzureKeyVault' ServerKeyType ServerKeyType `json:"serverKeyType,omitempty"` // URI - The URI of the key. If the ServerKeyType is AzureKeyVault, then the URI is required. URI *string `json:"uri,omitempty"` // Thumbprint - READ-ONLY; Thumbprint of the key. Thumbprint *string `json:"thumbprint,omitempty"` // CreationDate - READ-ONLY; The key creation date. CreationDate *date.Time `json:"creationDate,omitempty"` } // ManagedInstanceKeysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ManagedInstanceKeysCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedInstanceKeysCreateOrUpdateFuture) Result(client ManagedInstanceKeysClient) (mik ManagedInstanceKey, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceKeysCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if mik.Response.Response, err = future.GetResult(sender); err == nil && mik.Response.Response.StatusCode != http.StatusNoContent { mik, err = client.CreateOrUpdateResponder(mik.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysCreateOrUpdateFuture", "Result", mik.Response.Response, "Failure responding to request") } } return } // ManagedInstanceKeysDeleteFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ManagedInstanceKeysDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedInstanceKeysDeleteFuture) Result(client ManagedInstanceKeysClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstanceKeysDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceKeysDeleteFuture") return } ar.Response = future.Response() return } // ManagedInstanceListResult a list of managed instances. type ManagedInstanceListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ManagedInstance `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ManagedInstanceListResultIterator provides access to a complete listing of ManagedInstance values. type ManagedInstanceListResultIterator struct { i int page ManagedInstanceListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ManagedInstanceListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedInstanceListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ManagedInstanceListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ManagedInstanceListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ManagedInstanceListResultIterator) Response() ManagedInstanceListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ManagedInstanceListResultIterator) Value() ManagedInstance { if !iter.page.NotDone() { return ManagedInstance{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ManagedInstanceListResultIterator type. func NewManagedInstanceListResultIterator(page ManagedInstanceListResultPage) ManagedInstanceListResultIterator { return ManagedInstanceListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (milr ManagedInstanceListResult) IsEmpty() bool { return milr.Value == nil || len(*milr.Value) == 0 } // managedInstanceListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (milr ManagedInstanceListResult) managedInstanceListResultPreparer(ctx context.Context) (*http.Request, error) { if milr.NextLink == nil || len(to.String(milr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(milr.NextLink))) } // ManagedInstanceListResultPage contains a page of ManagedInstance values. type ManagedInstanceListResultPage struct { fn func(context.Context, ManagedInstanceListResult) (ManagedInstanceListResult, error) milr ManagedInstanceListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ManagedInstanceListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedInstanceListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.milr) if err != nil { return err } page.milr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ManagedInstanceListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ManagedInstanceListResultPage) NotDone() bool { return !page.milr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ManagedInstanceListResultPage) Response() ManagedInstanceListResult { return page.milr } // Values returns the slice of values for the current page or nil if there are no values. func (page ManagedInstanceListResultPage) Values() []ManagedInstance { if page.milr.IsEmpty() { return nil } return *page.milr.Value } // Creates a new instance of the ManagedInstanceListResultPage type. func NewManagedInstanceListResultPage(getNextPage func(context.Context, ManagedInstanceListResult) (ManagedInstanceListResult, error)) ManagedInstanceListResultPage { return ManagedInstanceListResultPage{fn: getNextPage} } // ManagedInstancePairInfo pairs of Managed Instances in the failover group. type ManagedInstancePairInfo struct { // PrimaryManagedInstanceID - Id of Primary Managed Instance in pair. PrimaryManagedInstanceID *string `json:"primaryManagedInstanceId,omitempty"` // PartnerManagedInstanceID - Id of Partner Managed Instance in pair. PartnerManagedInstanceID *string `json:"partnerManagedInstanceId,omitempty"` } // ManagedInstanceProperties the properties of a managed instance. type ManagedInstanceProperties struct { // ManagedInstanceCreateMode - Specifies the mode of database creation. // // Default: Regular instance creation. // // Restore: Creates an instance by restoring a set of backups to specific point in time. RestorePointInTime and SourceManagedInstanceId must be specified. Possible values include: 'ManagedServerCreateModeDefault', 'ManagedServerCreateModePointInTimeRestore' ManagedInstanceCreateMode ManagedServerCreateMode `json:"managedInstanceCreateMode,omitempty"` // FullyQualifiedDomainName - READ-ONLY; The fully qualified domain name of the managed instance. FullyQualifiedDomainName *string `json:"fullyQualifiedDomainName,omitempty"` // AdministratorLogin - Administrator username for the managed instance. Can only be specified when the managed instance is being created (and is required for creation). AdministratorLogin *string `json:"administratorLogin,omitempty"` // AdministratorLoginPassword - The administrator login password (required for managed instance creation). AdministratorLoginPassword *string `json:"administratorLoginPassword,omitempty"` // SubnetID - Subnet resource ID for the managed instance. SubnetID *string `json:"subnetId,omitempty"` // State - READ-ONLY; The state of the managed instance. State *string `json:"state,omitempty"` // LicenseType - The license type. Possible values are 'LicenseIncluded' (regular price inclusive of a new SQL license) and 'BasePrice' (discounted AHB price for bringing your own SQL licenses). Possible values include: 'ManagedInstanceLicenseTypeLicenseIncluded', 'ManagedInstanceLicenseTypeBasePrice' LicenseType ManagedInstanceLicenseType `json:"licenseType,omitempty"` // VCores - The number of vCores. Allowed values: 8, 16, 24, 32, 40, 64, 80. VCores *int32 `json:"vCores,omitempty"` // StorageSizeInGB - Storage size in GB. Minimum value: 32. Maximum value: 8192. Increments of 32 GB allowed only. StorageSizeInGB *int32 `json:"storageSizeInGB,omitempty"` // Collation - Collation of the managed instance. Collation *string `json:"collation,omitempty"` // DNSZone - READ-ONLY; The Dns Zone that the managed instance is in. DNSZone *string `json:"dnsZone,omitempty"` // DNSZonePartner - The resource id of another managed instance whose DNS zone this managed instance will share after creation. DNSZonePartner *string `json:"dnsZonePartner,omitempty"` // PublicDataEndpointEnabled - Whether or not the public data endpoint is enabled. PublicDataEndpointEnabled *bool `json:"publicDataEndpointEnabled,omitempty"` // SourceManagedInstanceID - The resource identifier of the source managed instance associated with create operation of this instance. SourceManagedInstanceID *string `json:"sourceManagedInstanceId,omitempty"` // RestorePointInTime - Specifies the point in time (ISO8601 format) of the source database that will be restored to create the new database. RestorePointInTime *date.Time `json:"restorePointInTime,omitempty"` // ProxyOverride - Connection type used for connecting to the instance. Possible values include: 'ManagedInstanceProxyOverrideProxy', 'ManagedInstanceProxyOverrideRedirect', 'ManagedInstanceProxyOverrideDefault' ProxyOverride ManagedInstanceProxyOverride `json:"proxyOverride,omitempty"` // TimezoneID - Id of the timezone. Allowed values are timezones supported by Windows. // Windows keeps details on supported timezones, including the id, in registry under // KEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones. // You can get those registry values via SQL Server by querying SELECT name AS timezone_id FROM sys.time_zone_info. // List of Ids can also be obtained by executing [System.TimeZoneInfo]::GetSystemTimeZones() in PowerShell. // An example of valid timezone id is "Pacific Standard Time" or "W. Europe Standard Time". TimezoneID *string `json:"timezoneId,omitempty"` // InstancePoolID - The Id of the instance pool this managed server belongs to. InstancePoolID *string `json:"instancePoolId,omitempty"` } // ManagedInstancesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ManagedInstancesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedInstancesCreateOrUpdateFuture) Result(client ManagedInstancesClient) (mi ManagedInstance, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstancesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedInstancesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if mi.Response.Response, err = future.GetResult(sender); err == nil && mi.Response.Response.StatusCode != http.StatusNoContent { mi, err = client.CreateOrUpdateResponder(mi.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstancesCreateOrUpdateFuture", "Result", mi.Response.Response, "Failure responding to request") } } return } // ManagedInstancesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ManagedInstancesDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedInstancesDeleteFuture) Result(client ManagedInstancesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstancesDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedInstancesDeleteFuture") return } ar.Response = future.Response() return } // ManagedInstancesUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ManagedInstancesUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedInstancesUpdateFuture) Result(client ManagedInstancesClient) (mi ManagedInstance, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstancesUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedInstancesUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if mi.Response.Response, err = future.GetResult(sender); err == nil && mi.Response.Response.StatusCode != http.StatusNoContent { mi, err = client.UpdateResponder(mi.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstancesUpdateFuture", "Result", mi.Response.Response, "Failure responding to request") } } return } // ManagedInstanceTdeCertificatesCreateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ManagedInstanceTdeCertificatesCreateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedInstanceTdeCertificatesCreateFuture) Result(client ManagedInstanceTdeCertificatesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedInstanceTdeCertificatesCreateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedInstanceTdeCertificatesCreateFuture") return } ar.Response = future.Response() return } // ManagedInstanceUpdate an update request for an Azure SQL Database managed instance. type ManagedInstanceUpdate struct { // Sku - Managed instance sku Sku *Sku `json:"sku,omitempty"` // ManagedInstanceProperties - Resource properties. *ManagedInstanceProperties `json:"properties,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` } // MarshalJSON is the custom marshaler for ManagedInstanceUpdate. func (miu ManagedInstanceUpdate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if miu.Sku != nil { objectMap["sku"] = miu.Sku } if miu.ManagedInstanceProperties != nil { objectMap["properties"] = miu.ManagedInstanceProperties } if miu.Tags != nil { objectMap["tags"] = miu.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedInstanceUpdate struct. func (miu *ManagedInstanceUpdate) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "sku": if v != nil { var sku Sku err = json.Unmarshal(*v, &sku) if err != nil { return err } miu.Sku = &sku } case "properties": if v != nil { var managedInstanceProperties ManagedInstanceProperties err = json.Unmarshal(*v, &managedInstanceProperties) if err != nil { return err } miu.ManagedInstanceProperties = &managedInstanceProperties } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } miu.Tags = tags } } } return nil } // ManagedInstanceVcoresCapability the managed instance virtual cores capability. type ManagedInstanceVcoresCapability struct { // Name - READ-ONLY; The virtual cores identifier. Name *string `json:"name,omitempty"` // Value - READ-ONLY; The virtual cores value. Value *int32 `json:"value,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ManagedInstanceVersionCapability the managed instance capability type ManagedInstanceVersionCapability struct { // Name - READ-ONLY; The server version name. Name *string `json:"name,omitempty"` // SupportedEditions - READ-ONLY; The list of supported managed instance editions. SupportedEditions *[]ManagedInstanceEditionCapability `json:"supportedEditions,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ManagedInstanceVulnerabilityAssessment a managed instance vulnerability assessment. type ManagedInstanceVulnerabilityAssessment struct { autorest.Response `json:"-"` // ManagedInstanceVulnerabilityAssessmentProperties - Resource properties. *ManagedInstanceVulnerabilityAssessmentProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ManagedInstanceVulnerabilityAssessment. func (miva ManagedInstanceVulnerabilityAssessment) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if miva.ManagedInstanceVulnerabilityAssessmentProperties != nil { objectMap["properties"] = miva.ManagedInstanceVulnerabilityAssessmentProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedInstanceVulnerabilityAssessment struct. func (miva *ManagedInstanceVulnerabilityAssessment) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var managedInstanceVulnerabilityAssessmentProperties ManagedInstanceVulnerabilityAssessmentProperties err = json.Unmarshal(*v, &managedInstanceVulnerabilityAssessmentProperties) if err != nil { return err } miva.ManagedInstanceVulnerabilityAssessmentProperties = &managedInstanceVulnerabilityAssessmentProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } miva.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } miva.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } miva.Type = &typeVar } } } return nil } // ManagedInstanceVulnerabilityAssessmentListResult a list of the ManagedInstance's vulnerability // assessments. type ManagedInstanceVulnerabilityAssessmentListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ManagedInstanceVulnerabilityAssessment `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ManagedInstanceVulnerabilityAssessmentListResultIterator provides access to a complete listing of // ManagedInstanceVulnerabilityAssessment values. type ManagedInstanceVulnerabilityAssessmentListResultIterator struct { i int page ManagedInstanceVulnerabilityAssessmentListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ManagedInstanceVulnerabilityAssessmentListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedInstanceVulnerabilityAssessmentListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ManagedInstanceVulnerabilityAssessmentListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ManagedInstanceVulnerabilityAssessmentListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ManagedInstanceVulnerabilityAssessmentListResultIterator) Response() ManagedInstanceVulnerabilityAssessmentListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ManagedInstanceVulnerabilityAssessmentListResultIterator) Value() ManagedInstanceVulnerabilityAssessment { if !iter.page.NotDone() { return ManagedInstanceVulnerabilityAssessment{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ManagedInstanceVulnerabilityAssessmentListResultIterator type. func NewManagedInstanceVulnerabilityAssessmentListResultIterator(page ManagedInstanceVulnerabilityAssessmentListResultPage) ManagedInstanceVulnerabilityAssessmentListResultIterator { return ManagedInstanceVulnerabilityAssessmentListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (mivalr ManagedInstanceVulnerabilityAssessmentListResult) IsEmpty() bool { return mivalr.Value == nil || len(*mivalr.Value) == 0 } // managedInstanceVulnerabilityAssessmentListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (mivalr ManagedInstanceVulnerabilityAssessmentListResult) managedInstanceVulnerabilityAssessmentListResultPreparer(ctx context.Context) (*http.Request, error) { if mivalr.NextLink == nil || len(to.String(mivalr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(mivalr.NextLink))) } // ManagedInstanceVulnerabilityAssessmentListResultPage contains a page of // ManagedInstanceVulnerabilityAssessment values. type ManagedInstanceVulnerabilityAssessmentListResultPage struct { fn func(context.Context, ManagedInstanceVulnerabilityAssessmentListResult) (ManagedInstanceVulnerabilityAssessmentListResult, error) mivalr ManagedInstanceVulnerabilityAssessmentListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ManagedInstanceVulnerabilityAssessmentListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedInstanceVulnerabilityAssessmentListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.mivalr) if err != nil { return err } page.mivalr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ManagedInstanceVulnerabilityAssessmentListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ManagedInstanceVulnerabilityAssessmentListResultPage) NotDone() bool { return !page.mivalr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ManagedInstanceVulnerabilityAssessmentListResultPage) Response() ManagedInstanceVulnerabilityAssessmentListResult { return page.mivalr } // Values returns the slice of values for the current page or nil if there are no values. func (page ManagedInstanceVulnerabilityAssessmentListResultPage) Values() []ManagedInstanceVulnerabilityAssessment { if page.mivalr.IsEmpty() { return nil } return *page.mivalr.Value } // Creates a new instance of the ManagedInstanceVulnerabilityAssessmentListResultPage type. func NewManagedInstanceVulnerabilityAssessmentListResultPage(getNextPage func(context.Context, ManagedInstanceVulnerabilityAssessmentListResult) (ManagedInstanceVulnerabilityAssessmentListResult, error)) ManagedInstanceVulnerabilityAssessmentListResultPage { return ManagedInstanceVulnerabilityAssessmentListResultPage{fn: getNextPage} } // ManagedInstanceVulnerabilityAssessmentProperties properties of a managed instance vulnerability // assessment. type ManagedInstanceVulnerabilityAssessmentProperties struct { // StorageContainerPath - A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/). StorageContainerPath *string `json:"storageContainerPath,omitempty"` // StorageContainerSasKey - A shared access signature (SAS Key) that has write access to the blob container specified in 'storageContainerPath' parameter. If 'storageAccountAccessKey' isn't specified, StorageContainerSasKey is required. StorageContainerSasKey *string `json:"storageContainerSasKey,omitempty"` // StorageAccountAccessKey - Specifies the identifier key of the storage account for vulnerability assessment scan results. If 'StorageContainerSasKey' isn't specified, storageAccountAccessKey is required. StorageAccountAccessKey *string `json:"storageAccountAccessKey,omitempty"` // RecurringScans - The recurring scans settings RecurringScans *VulnerabilityAssessmentRecurringScansProperties `json:"recurringScans,omitempty"` } // ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesCreateOrUpdateFuture an abstraction for // monitoring and retrieving the results of a long-running operation. type ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesCreateOrUpdateFuture) Result(client ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesClient) (mbstrp ManagedBackupShortTermRetentionPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if mbstrp.Response.Response, err = future.GetResult(sender); err == nil && mbstrp.Response.Response.StatusCode != http.StatusNoContent { mbstrp, err = client.CreateOrUpdateResponder(mbstrp.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesCreateOrUpdateFuture", "Result", mbstrp.Response.Response, "Failure responding to request") } } return } // ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesUpdateFuture an abstraction for // monitoring and retrieving the results of a long-running operation. type ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesUpdateFuture) Result(client ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesClient) (mbstrp ManagedBackupShortTermRetentionPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if mbstrp.Response.Response, err = future.GetResult(sender); err == nil && mbstrp.Response.Response.StatusCode != http.StatusNoContent { mbstrp, err = client.UpdateResponder(mbstrp.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedRestorableDroppedDatabaseBackupShortTermRetentionPoliciesUpdateFuture", "Result", mbstrp.Response.Response, "Failure responding to request") } } return } // ManagedServerSecurityAlertPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the // results of a long-running operation. type ManagedServerSecurityAlertPoliciesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ManagedServerSecurityAlertPoliciesCreateOrUpdateFuture) Result(client ManagedServerSecurityAlertPoliciesClient) (mssap ManagedServerSecurityAlertPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedServerSecurityAlertPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ManagedServerSecurityAlertPoliciesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if mssap.Response.Response, err = future.GetResult(sender); err == nil && mssap.Response.Response.StatusCode != http.StatusNoContent { mssap, err = client.CreateOrUpdateResponder(mssap.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ManagedServerSecurityAlertPoliciesCreateOrUpdateFuture", "Result", mssap.Response.Response, "Failure responding to request") } } return } // ManagedServerSecurityAlertPolicy a managed server security alert policy. type ManagedServerSecurityAlertPolicy struct { autorest.Response `json:"-"` // SecurityAlertPolicyProperties - Resource properties. *SecurityAlertPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ManagedServerSecurityAlertPolicy. func (mssap ManagedServerSecurityAlertPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if mssap.SecurityAlertPolicyProperties != nil { objectMap["properties"] = mssap.SecurityAlertPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ManagedServerSecurityAlertPolicy struct. func (mssap *ManagedServerSecurityAlertPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var securityAlertPolicyProperties SecurityAlertPolicyProperties err = json.Unmarshal(*v, &securityAlertPolicyProperties) if err != nil { return err } mssap.SecurityAlertPolicyProperties = &securityAlertPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } mssap.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } mssap.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } mssap.Type = &typeVar } } } return nil } // ManagedServerSecurityAlertPolicyListResult a list of the managed Server's security alert policies. type ManagedServerSecurityAlertPolicyListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ManagedServerSecurityAlertPolicy `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ManagedServerSecurityAlertPolicyListResultIterator provides access to a complete listing of // ManagedServerSecurityAlertPolicy values. type ManagedServerSecurityAlertPolicyListResultIterator struct { i int page ManagedServerSecurityAlertPolicyListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ManagedServerSecurityAlertPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedServerSecurityAlertPolicyListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ManagedServerSecurityAlertPolicyListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ManagedServerSecurityAlertPolicyListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ManagedServerSecurityAlertPolicyListResultIterator) Response() ManagedServerSecurityAlertPolicyListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ManagedServerSecurityAlertPolicyListResultIterator) Value() ManagedServerSecurityAlertPolicy { if !iter.page.NotDone() { return ManagedServerSecurityAlertPolicy{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ManagedServerSecurityAlertPolicyListResultIterator type. func NewManagedServerSecurityAlertPolicyListResultIterator(page ManagedServerSecurityAlertPolicyListResultPage) ManagedServerSecurityAlertPolicyListResultIterator { return ManagedServerSecurityAlertPolicyListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (mssaplr ManagedServerSecurityAlertPolicyListResult) IsEmpty() bool { return mssaplr.Value == nil || len(*mssaplr.Value) == 0 } // managedServerSecurityAlertPolicyListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (mssaplr ManagedServerSecurityAlertPolicyListResult) managedServerSecurityAlertPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { if mssaplr.NextLink == nil || len(to.String(mssaplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(mssaplr.NextLink))) } // ManagedServerSecurityAlertPolicyListResultPage contains a page of ManagedServerSecurityAlertPolicy // values. type ManagedServerSecurityAlertPolicyListResultPage struct { fn func(context.Context, ManagedServerSecurityAlertPolicyListResult) (ManagedServerSecurityAlertPolicyListResult, error) mssaplr ManagedServerSecurityAlertPolicyListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ManagedServerSecurityAlertPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ManagedServerSecurityAlertPolicyListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.mssaplr) if err != nil { return err } page.mssaplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ManagedServerSecurityAlertPolicyListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ManagedServerSecurityAlertPolicyListResultPage) NotDone() bool { return !page.mssaplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ManagedServerSecurityAlertPolicyListResultPage) Response() ManagedServerSecurityAlertPolicyListResult { return page.mssaplr } // Values returns the slice of values for the current page or nil if there are no values. func (page ManagedServerSecurityAlertPolicyListResultPage) Values() []ManagedServerSecurityAlertPolicy { if page.mssaplr.IsEmpty() { return nil } return *page.mssaplr.Value } // Creates a new instance of the ManagedServerSecurityAlertPolicyListResultPage type. func NewManagedServerSecurityAlertPolicyListResultPage(getNextPage func(context.Context, ManagedServerSecurityAlertPolicyListResult) (ManagedServerSecurityAlertPolicyListResult, error)) ManagedServerSecurityAlertPolicyListResultPage { return ManagedServerSecurityAlertPolicyListResultPage{fn: getNextPage} } // MaxSizeCapability the maximum size capability. type MaxSizeCapability struct { // Limit - READ-ONLY; The maximum size limit (see 'unit' for the units). Limit *int32 `json:"limit,omitempty"` // Unit - READ-ONLY; The units that the limit is expressed in. Possible values include: 'MaxSizeUnitMegabytes', 'MaxSizeUnitGigabytes', 'MaxSizeUnitTerabytes', 'MaxSizeUnitPetabytes' Unit MaxSizeUnit `json:"unit,omitempty"` } // MaxSizeRangeCapability the maximum size range capability. type MaxSizeRangeCapability struct { // MinValue - READ-ONLY; Minimum value. MinValue *MaxSizeCapability `json:"minValue,omitempty"` // MaxValue - READ-ONLY; Maximum value. MaxValue *MaxSizeCapability `json:"maxValue,omitempty"` // ScaleSize - READ-ONLY; Scale/step size for discrete values between the minimum value and the maximum value. ScaleSize *MaxSizeCapability `json:"scaleSize,omitempty"` // LogSize - READ-ONLY; Size of transaction log. LogSize *LogSizeCapability `json:"logSize,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // Metric database metrics. type Metric struct { // StartTime - READ-ONLY; The start time for the metric (ISO-8601 format). StartTime *date.Time `json:"startTime,omitempty"` // EndTime - READ-ONLY; The end time for the metric (ISO-8601 format). EndTime *date.Time `json:"endTime,omitempty"` // TimeGrain - READ-ONLY; The time step to be used to summarize the metric values. TimeGrain *string `json:"timeGrain,omitempty"` // Unit - READ-ONLY; The unit of the metric. Possible values include: 'UnitTypeCount', 'UnitTypeBytes', 'UnitTypeSeconds', 'UnitTypePercent', 'UnitTypeCountPerSecond', 'UnitTypeBytesPerSecond' Unit UnitType `json:"unit,omitempty"` // Name - READ-ONLY; The name information for the metric. Name *MetricName `json:"name,omitempty"` // MetricValues - READ-ONLY; The metric values for the specified time window and timestep. MetricValues *[]MetricValue `json:"metricValues,omitempty"` } // MetricAvailability a metric availability value. type MetricAvailability struct { // Retention - READ-ONLY; The length of retention for the database metric. Retention *string `json:"retention,omitempty"` // TimeGrain - READ-ONLY; The granularity of the database metric. TimeGrain *string `json:"timeGrain,omitempty"` } // MetricDefinition a database metric definition. type MetricDefinition struct { // Name - READ-ONLY; The name information for the metric. Name *MetricName `json:"name,omitempty"` // PrimaryAggregationType - READ-ONLY; The primary aggregation type defining how metric values are displayed. Possible values include: 'None', 'Average', 'Count', 'Minimum', 'Maximum', 'Total' PrimaryAggregationType PrimaryAggregationType `json:"primaryAggregationType,omitempty"` // ResourceURI - READ-ONLY; The resource uri of the database. ResourceURI *string `json:"resourceUri,omitempty"` // Unit - READ-ONLY; The unit of the metric. Possible values include: 'UnitDefinitionTypeCount', 'UnitDefinitionTypeBytes', 'UnitDefinitionTypeSeconds', 'UnitDefinitionTypePercent', 'UnitDefinitionTypeCountPerSecond', 'UnitDefinitionTypeBytesPerSecond' Unit UnitDefinitionType `json:"unit,omitempty"` // MetricAvailabilities - READ-ONLY; The list of database metric availabilities for the metric. MetricAvailabilities *[]MetricAvailability `json:"metricAvailabilities,omitempty"` } // MetricDefinitionListResult the response to a list database metric definitions request. type MetricDefinitionListResult struct { autorest.Response `json:"-"` // Value - The list of metric definitions for the database. Value *[]MetricDefinition `json:"value,omitempty"` } // MetricListResult the response to a list database metrics request. type MetricListResult struct { autorest.Response `json:"-"` // Value - The list of metrics for the database. Value *[]Metric `json:"value,omitempty"` } // MetricName a database metric name. type MetricName struct { // Value - READ-ONLY; The name of the database metric. Value *string `json:"value,omitempty"` // LocalizedValue - READ-ONLY; The friendly name of the database metric. LocalizedValue *string `json:"localizedValue,omitempty"` } // MetricValue represents database metrics. type MetricValue struct { // Count - READ-ONLY; The number of values for the metric. Count *float64 `json:"count,omitempty"` // Average - READ-ONLY; The average value of the metric. Average *float64 `json:"average,omitempty"` // Maximum - READ-ONLY; The max value of the metric. Maximum *float64 `json:"maximum,omitempty"` // Minimum - READ-ONLY; The min value of the metric. Minimum *float64 `json:"minimum,omitempty"` // Timestamp - READ-ONLY; The metric timestamp (ISO-8601 format). Timestamp *date.Time `json:"timestamp,omitempty"` // Total - READ-ONLY; The total value of the metric. Total *float64 `json:"total,omitempty"` } // Name ARM Usage Name type Name struct { // Value - Usage name value Value *string `json:"value,omitempty"` // LocalizedValue - Usage name localized value. LocalizedValue *string `json:"localizedValue,omitempty"` } // Operation SQL REST API operation definition. type Operation struct { // Name - READ-ONLY; The name of the operation being performed on this particular object. Name *string `json:"name,omitempty"` // Display - READ-ONLY; The localized display information for this particular operation / action. Display *OperationDisplay `json:"display,omitempty"` // Origin - READ-ONLY; The intended executor of the operation. Possible values include: 'OperationOriginUser', 'OperationOriginSystem' Origin OperationOrigin `json:"origin,omitempty"` // Properties - READ-ONLY; Additional descriptions for the operation. Properties map[string]interface{} `json:"properties"` } // MarshalJSON is the custom marshaler for Operation. func (o Operation) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) return json.Marshal(objectMap) } // OperationDisplay display metadata associated with the operation. type OperationDisplay struct { // Provider - READ-ONLY; The localized friendly form of the resource provider name. Provider *string `json:"provider,omitempty"` // Resource - READ-ONLY; The localized friendly form of the resource type related to this action/operation. Resource *string `json:"resource,omitempty"` // Operation - READ-ONLY; The localized friendly name for the operation. Operation *string `json:"operation,omitempty"` // Description - READ-ONLY; The localized friendly description for the operation. Description *string `json:"description,omitempty"` } // OperationImpact the impact of an operation, both in absolute and relative terms. type OperationImpact struct { // Name - READ-ONLY; The name of the impact dimension. Name *string `json:"name,omitempty"` // Unit - READ-ONLY; The unit in which estimated impact to dimension is measured. Unit *string `json:"unit,omitempty"` // ChangeValueAbsolute - READ-ONLY; The absolute impact to dimension. ChangeValueAbsolute *float64 `json:"changeValueAbsolute,omitempty"` // ChangeValueRelative - READ-ONLY; The relative impact to dimension (null if not applicable) ChangeValueRelative *float64 `json:"changeValueRelative,omitempty"` } // OperationListResult result of the request to list SQL operations. type OperationListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]Operation `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // OperationListResultIterator provides access to a complete listing of Operation values. type OperationListResultIterator struct { i int page OperationListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *OperationListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *OperationListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter OperationListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter OperationListResultIterator) Response() OperationListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter OperationListResultIterator) Value() Operation { if !iter.page.NotDone() { return Operation{} } return iter.page.Values()[iter.i] } // Creates a new instance of the OperationListResultIterator type. func NewOperationListResultIterator(page OperationListResultPage) OperationListResultIterator { return OperationListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (olr OperationListResult) IsEmpty() bool { return olr.Value == nil || len(*olr.Value) == 0 } // operationListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (olr OperationListResult) operationListResultPreparer(ctx context.Context) (*http.Request, error) { if olr.NextLink == nil || len(to.String(olr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(olr.NextLink))) } // OperationListResultPage contains a page of Operation values. type OperationListResultPage struct { fn func(context.Context, OperationListResult) (OperationListResult, error) olr OperationListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *OperationListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/OperationListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.olr) if err != nil { return err } page.olr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *OperationListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page OperationListResultPage) NotDone() bool { return !page.olr.IsEmpty() } // Response returns the raw server response from the last page request. func (page OperationListResultPage) Response() OperationListResult { return page.olr } // Values returns the slice of values for the current page or nil if there are no values. func (page OperationListResultPage) Values() []Operation { if page.olr.IsEmpty() { return nil } return *page.olr.Value } // Creates a new instance of the OperationListResultPage type. func NewOperationListResultPage(getNextPage func(context.Context, OperationListResult) (OperationListResult, error)) OperationListResultPage { return OperationListResultPage{fn: getNextPage} } // PartnerInfo partner server information for the failover group. type PartnerInfo struct { // ID - Resource identifier of the partner server. ID *string `json:"id,omitempty"` // Location - READ-ONLY; Geo location of the partner server. Location *string `json:"location,omitempty"` // ReplicationRole - READ-ONLY; Replication role of the partner server. Possible values include: 'Primary', 'Secondary' ReplicationRole FailoverGroupReplicationRole `json:"replicationRole,omitempty"` } // PartnerRegionInfo partner region information for the failover group. type PartnerRegionInfo struct { // Location - Geo location of the partner managed instances. Location *string `json:"location,omitempty"` // ReplicationRole - READ-ONLY; Replication role of the partner managed instances. Possible values include: 'InstanceFailoverGroupReplicationRolePrimary', 'InstanceFailoverGroupReplicationRoleSecondary' ReplicationRole InstanceFailoverGroupReplicationRole `json:"replicationRole,omitempty"` } // PerformanceLevelCapability the performance level capability. type PerformanceLevelCapability struct { // Value - READ-ONLY; Performance level value. Value *float64 `json:"value,omitempty"` // Unit - READ-ONLY; Unit type used to measure performance level. Possible values include: 'DTU', 'VCores' Unit PerformanceLevelUnit `json:"unit,omitempty"` } // PrivateEndpointConnection a private endpoint connection type PrivateEndpointConnection struct { autorest.Response `json:"-"` // PrivateEndpointConnectionProperties - Resource properties. *PrivateEndpointConnectionProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for PrivateEndpointConnection. func (pec PrivateEndpointConnection) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if pec.PrivateEndpointConnectionProperties != nil { objectMap["properties"] = pec.PrivateEndpointConnectionProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for PrivateEndpointConnection struct. func (pec *PrivateEndpointConnection) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var privateEndpointConnectionProperties PrivateEndpointConnectionProperties err = json.Unmarshal(*v, &privateEndpointConnectionProperties) if err != nil { return err } pec.PrivateEndpointConnectionProperties = &privateEndpointConnectionProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } pec.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } pec.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } pec.Type = &typeVar } } } return nil } // PrivateEndpointConnectionListResult a list of private endpoint connections. type PrivateEndpointConnectionListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]PrivateEndpointConnection `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // PrivateEndpointConnectionListResultIterator provides access to a complete listing of // PrivateEndpointConnection values. type PrivateEndpointConnectionListResultIterator struct { i int page PrivateEndpointConnectionListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *PrivateEndpointConnectionListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *PrivateEndpointConnectionListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter PrivateEndpointConnectionListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter PrivateEndpointConnectionListResultIterator) Response() PrivateEndpointConnectionListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter PrivateEndpointConnectionListResultIterator) Value() PrivateEndpointConnection { if !iter.page.NotDone() { return PrivateEndpointConnection{} } return iter.page.Values()[iter.i] } // Creates a new instance of the PrivateEndpointConnectionListResultIterator type. func NewPrivateEndpointConnectionListResultIterator(page PrivateEndpointConnectionListResultPage) PrivateEndpointConnectionListResultIterator { return PrivateEndpointConnectionListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (peclr PrivateEndpointConnectionListResult) IsEmpty() bool { return peclr.Value == nil || len(*peclr.Value) == 0 } // privateEndpointConnectionListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (peclr PrivateEndpointConnectionListResult) privateEndpointConnectionListResultPreparer(ctx context.Context) (*http.Request, error) { if peclr.NextLink == nil || len(to.String(peclr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(peclr.NextLink))) } // PrivateEndpointConnectionListResultPage contains a page of PrivateEndpointConnection values. type PrivateEndpointConnectionListResultPage struct { fn func(context.Context, PrivateEndpointConnectionListResult) (PrivateEndpointConnectionListResult, error) peclr PrivateEndpointConnectionListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *PrivateEndpointConnectionListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/PrivateEndpointConnectionListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.peclr) if err != nil { return err } page.peclr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *PrivateEndpointConnectionListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page PrivateEndpointConnectionListResultPage) NotDone() bool { return !page.peclr.IsEmpty() } // Response returns the raw server response from the last page request. func (page PrivateEndpointConnectionListResultPage) Response() PrivateEndpointConnectionListResult { return page.peclr } // Values returns the slice of values for the current page or nil if there are no values. func (page PrivateEndpointConnectionListResultPage) Values() []PrivateEndpointConnection { if page.peclr.IsEmpty() { return nil } return *page.peclr.Value } // Creates a new instance of the PrivateEndpointConnectionListResultPage type. func NewPrivateEndpointConnectionListResultPage(getNextPage func(context.Context, PrivateEndpointConnectionListResult) (PrivateEndpointConnectionListResult, error)) PrivateEndpointConnectionListResultPage { return PrivateEndpointConnectionListResultPage{fn: getNextPage} } // PrivateEndpointConnectionProperties properties of a private endpoint connection. type PrivateEndpointConnectionProperties struct { // PrivateEndpoint - Private endpoint which the connection belongs to. PrivateEndpoint *PrivateEndpointProperty `json:"privateEndpoint,omitempty"` // PrivateLinkServiceConnectionState - Connection state of the private endpoint connection. PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionStateProperty `json:"privateLinkServiceConnectionState,omitempty"` // ProvisioningState - READ-ONLY; State of the private endpoint connection. ProvisioningState *string `json:"provisioningState,omitempty"` } // PrivateEndpointConnectionsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results // of a long-running operation. type PrivateEndpointConnectionsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *PrivateEndpointConnectionsCreateOrUpdateFuture) Result(client PrivateEndpointConnectionsClient) (pec PrivateEndpointConnection, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.PrivateEndpointConnectionsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.PrivateEndpointConnectionsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if pec.Response.Response, err = future.GetResult(sender); err == nil && pec.Response.Response.StatusCode != http.StatusNoContent { pec, err = client.CreateOrUpdateResponder(pec.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.PrivateEndpointConnectionsCreateOrUpdateFuture", "Result", pec.Response.Response, "Failure responding to request") } } return } // PrivateEndpointConnectionsDeleteFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type PrivateEndpointConnectionsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *PrivateEndpointConnectionsDeleteFuture) Result(client PrivateEndpointConnectionsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.PrivateEndpointConnectionsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.PrivateEndpointConnectionsDeleteFuture") return } ar.Response = future.Response() return } // PrivateEndpointProperty ... type PrivateEndpointProperty struct { // ID - Resource id of the private endpoint. ID *string `json:"id,omitempty"` } // PrivateLinkResource a private link resource type PrivateLinkResource struct { autorest.Response `json:"-"` // Properties - READ-ONLY; The private link resource group id. Properties *PrivateLinkResourceProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // PrivateLinkResourceListResult a list of private link resources type PrivateLinkResourceListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]PrivateLinkResource `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // PrivateLinkResourceListResultIterator provides access to a complete listing of PrivateLinkResource // values. type PrivateLinkResourceListResultIterator struct { i int page PrivateLinkResourceListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *PrivateLinkResourceListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourceListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *PrivateLinkResourceListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter PrivateLinkResourceListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter PrivateLinkResourceListResultIterator) Response() PrivateLinkResourceListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter PrivateLinkResourceListResultIterator) Value() PrivateLinkResource { if !iter.page.NotDone() { return PrivateLinkResource{} } return iter.page.Values()[iter.i] } // Creates a new instance of the PrivateLinkResourceListResultIterator type. func NewPrivateLinkResourceListResultIterator(page PrivateLinkResourceListResultPage) PrivateLinkResourceListResultIterator { return PrivateLinkResourceListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (plrlr PrivateLinkResourceListResult) IsEmpty() bool { return plrlr.Value == nil || len(*plrlr.Value) == 0 } // privateLinkResourceListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (plrlr PrivateLinkResourceListResult) privateLinkResourceListResultPreparer(ctx context.Context) (*http.Request, error) { if plrlr.NextLink == nil || len(to.String(plrlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(plrlr.NextLink))) } // PrivateLinkResourceListResultPage contains a page of PrivateLinkResource values. type PrivateLinkResourceListResultPage struct { fn func(context.Context, PrivateLinkResourceListResult) (PrivateLinkResourceListResult, error) plrlr PrivateLinkResourceListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *PrivateLinkResourceListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/PrivateLinkResourceListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.plrlr) if err != nil { return err } page.plrlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *PrivateLinkResourceListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page PrivateLinkResourceListResultPage) NotDone() bool { return !page.plrlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page PrivateLinkResourceListResultPage) Response() PrivateLinkResourceListResult { return page.plrlr } // Values returns the slice of values for the current page or nil if there are no values. func (page PrivateLinkResourceListResultPage) Values() []PrivateLinkResource { if page.plrlr.IsEmpty() { return nil } return *page.plrlr.Value } // Creates a new instance of the PrivateLinkResourceListResultPage type. func NewPrivateLinkResourceListResultPage(getNextPage func(context.Context, PrivateLinkResourceListResult) (PrivateLinkResourceListResult, error)) PrivateLinkResourceListResultPage { return PrivateLinkResourceListResultPage{fn: getNextPage} } // PrivateLinkResourceProperties properties of a private link resource. type PrivateLinkResourceProperties struct { // GroupID - READ-ONLY; The private link resource group id. GroupID *string `json:"groupId,omitempty"` // RequiredMembers - READ-ONLY; The private link resource required member names. RequiredMembers *[]string `json:"requiredMembers,omitempty"` } // PrivateLinkServiceConnectionStateProperty ... type PrivateLinkServiceConnectionStateProperty struct { // Status - The private link service connection status. Status *string `json:"status,omitempty"` // Description - The private link service connection description. Description *string `json:"description,omitempty"` // ActionsRequired - READ-ONLY; The actions required for private link service connection. ActionsRequired *string `json:"actionsRequired,omitempty"` } // ProxyResource ARM proxy resource. type ProxyResource struct { // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // RecommendedElasticPool represents a recommended elastic pool. type RecommendedElasticPool struct { autorest.Response `json:"-"` // RecommendedElasticPoolProperties - The properties representing the resource. *RecommendedElasticPoolProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for RecommendedElasticPool. func (rep RecommendedElasticPool) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if rep.RecommendedElasticPoolProperties != nil { objectMap["properties"] = rep.RecommendedElasticPoolProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for RecommendedElasticPool struct. func (rep *RecommendedElasticPool) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var recommendedElasticPoolProperties RecommendedElasticPoolProperties err = json.Unmarshal(*v, &recommendedElasticPoolProperties) if err != nil { return err } rep.RecommendedElasticPoolProperties = &recommendedElasticPoolProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } rep.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } rep.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } rep.Type = &typeVar } } } return nil } // RecommendedElasticPoolListMetricsResult represents the response to a list recommended elastic pool // metrics request. type RecommendedElasticPoolListMetricsResult struct { autorest.Response `json:"-"` // Value - The list of recommended elastic pools metrics. Value *[]RecommendedElasticPoolMetric `json:"value,omitempty"` } // RecommendedElasticPoolListResult represents the response to a list recommended elastic pool request. type RecommendedElasticPoolListResult struct { autorest.Response `json:"-"` // Value - The list of recommended elastic pools hosted in the server. Value *[]RecommendedElasticPool `json:"value,omitempty"` } // RecommendedElasticPoolMetric represents recommended elastic pool metric. type RecommendedElasticPoolMetric struct { // DateTime - The time of metric (ISO8601 format). DateTime *date.Time `json:"dateTime,omitempty"` // Dtu - Gets or sets the DTUs (Database Transaction Units). See https://azure.microsoft.com/documentation/articles/sql-database-what-is-a-dtu/ Dtu *float64 `json:"dtu,omitempty"` // SizeGB - Gets or sets size in gigabytes. SizeGB *float64 `json:"sizeGB,omitempty"` } // RecommendedElasticPoolProperties represents the properties of a recommended elastic pool. type RecommendedElasticPoolProperties struct { // DatabaseEdition - READ-ONLY; The edition of the recommended elastic pool. The ElasticPoolEdition enumeration contains all the valid editions. Possible values include: 'ElasticPoolEditionBasic', 'ElasticPoolEditionStandard', 'ElasticPoolEditionPremium', 'ElasticPoolEditionGeneralPurpose', 'ElasticPoolEditionBusinessCritical' DatabaseEdition ElasticPoolEdition `json:"databaseEdition,omitempty"` // Dtu - The DTU for the recommended elastic pool. Dtu *float64 `json:"dtu,omitempty"` // DatabaseDtuMin - The minimum DTU for the database. DatabaseDtuMin *float64 `json:"databaseDtuMin,omitempty"` // DatabaseDtuMax - The maximum DTU for the database. DatabaseDtuMax *float64 `json:"databaseDtuMax,omitempty"` // StorageMB - Gets storage size in megabytes. StorageMB *float64 `json:"storageMB,omitempty"` // ObservationPeriodStart - READ-ONLY; The observation period start (ISO8601 format). ObservationPeriodStart *date.Time `json:"observationPeriodStart,omitempty"` // ObservationPeriodEnd - READ-ONLY; The observation period start (ISO8601 format). ObservationPeriodEnd *date.Time `json:"observationPeriodEnd,omitempty"` // MaxObservedDtu - READ-ONLY; Gets maximum observed DTU. MaxObservedDtu *float64 `json:"maxObservedDtu,omitempty"` // MaxObservedStorageMB - READ-ONLY; Gets maximum observed storage in megabytes. MaxObservedStorageMB *float64 `json:"maxObservedStorageMB,omitempty"` // Databases - READ-ONLY; The list of databases in this pool. Expanded property Databases *[]TrackedResource `json:"databases,omitempty"` // Metrics - READ-ONLY; The list of databases housed in the server. Expanded property Metrics *[]RecommendedElasticPoolMetric `json:"metrics,omitempty"` } // RecommendedIndex represents a database recommended index. type RecommendedIndex struct { // RecommendedIndexProperties - READ-ONLY; The properties representing the resource. *RecommendedIndexProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for RecommendedIndex. func (ri RecommendedIndex) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for RecommendedIndex struct. func (ri *RecommendedIndex) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var recommendedIndexProperties RecommendedIndexProperties err = json.Unmarshal(*v, &recommendedIndexProperties) if err != nil { return err } ri.RecommendedIndexProperties = &recommendedIndexProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } ri.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } ri.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } ri.Type = &typeVar } } } return nil } // RecommendedIndexProperties represents the properties of a database recommended index. type RecommendedIndexProperties struct { // Action - READ-ONLY; The proposed index action. You can create a missing index, drop an unused index, or rebuild an existing index to improve its performance. Possible values include: 'Create', 'Drop', 'Rebuild' Action RecommendedIndexAction `json:"action,omitempty"` // State - READ-ONLY; The current recommendation state. Possible values include: 'Active', 'Pending', 'Executing', 'Verifying', 'PendingRevert', 'Reverting', 'Reverted', 'Ignored', 'Expired', 'Blocked', 'Success' State RecommendedIndexState `json:"state,omitempty"` // Created - READ-ONLY; The UTC datetime showing when this resource was created (ISO8601 format). Created *date.Time `json:"created,omitempty"` // LastModified - READ-ONLY; The UTC datetime of when was this resource last changed (ISO8601 format). LastModified *date.Time `json:"lastModified,omitempty"` // IndexType - READ-ONLY; The type of index (CLUSTERED, NONCLUSTERED, COLUMNSTORE, CLUSTERED COLUMNSTORE). Possible values include: 'CLUSTERED', 'NONCLUSTERED', 'COLUMNSTORE', 'CLUSTEREDCOLUMNSTORE' IndexType RecommendedIndexType `json:"indexType,omitempty"` // Schema - READ-ONLY; The schema where table to build index over resides Schema *string `json:"schema,omitempty"` // Table - READ-ONLY; The table on which to build index. Table *string `json:"table,omitempty"` // Columns - READ-ONLY; Columns over which to build index Columns *[]string `json:"columns,omitempty"` // IncludedColumns - READ-ONLY; The list of column names to be included in the index IncludedColumns *[]string `json:"includedColumns,omitempty"` // IndexScript - READ-ONLY; The full build index script IndexScript *string `json:"indexScript,omitempty"` // EstimatedImpact - READ-ONLY; The estimated impact of doing recommended index action. EstimatedImpact *[]OperationImpact `json:"estimatedImpact,omitempty"` // ReportedImpact - READ-ONLY; The values reported after index action is complete. ReportedImpact *[]OperationImpact `json:"reportedImpact,omitempty"` } // RecoverableDatabase a recoverable database type RecoverableDatabase struct { autorest.Response `json:"-"` // RecoverableDatabaseProperties - The properties of a recoverable database *RecoverableDatabaseProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for RecoverableDatabase. func (rd RecoverableDatabase) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if rd.RecoverableDatabaseProperties != nil { objectMap["properties"] = rd.RecoverableDatabaseProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for RecoverableDatabase struct. func (rd *RecoverableDatabase) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var recoverableDatabaseProperties RecoverableDatabaseProperties err = json.Unmarshal(*v, &recoverableDatabaseProperties) if err != nil { return err } rd.RecoverableDatabaseProperties = &recoverableDatabaseProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } rd.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } rd.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } rd.Type = &typeVar } } } return nil } // RecoverableDatabaseListResult the response to a list recoverable databases request type RecoverableDatabaseListResult struct { autorest.Response `json:"-"` // Value - A list of recoverable databases Value *[]RecoverableDatabase `json:"value,omitempty"` } // RecoverableDatabaseProperties the properties of a recoverable database type RecoverableDatabaseProperties struct { // Edition - READ-ONLY; The edition of the database Edition *string `json:"edition,omitempty"` // ServiceLevelObjective - READ-ONLY; The service level objective name of the database ServiceLevelObjective *string `json:"serviceLevelObjective,omitempty"` // ElasticPoolName - READ-ONLY; The elastic pool name of the database ElasticPoolName *string `json:"elasticPoolName,omitempty"` // LastAvailableBackupDate - READ-ONLY; The last available backup date of the database (ISO8601 format) LastAvailableBackupDate *date.Time `json:"lastAvailableBackupDate,omitempty"` } // RecoverableManagedDatabase a recoverable managed database resource. type RecoverableManagedDatabase struct { autorest.Response `json:"-"` // RecoverableManagedDatabaseProperties - Resource properties. *RecoverableManagedDatabaseProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for RecoverableManagedDatabase. func (rmd RecoverableManagedDatabase) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if rmd.RecoverableManagedDatabaseProperties != nil { objectMap["properties"] = rmd.RecoverableManagedDatabaseProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for RecoverableManagedDatabase struct. func (rmd *RecoverableManagedDatabase) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var recoverableManagedDatabaseProperties RecoverableManagedDatabaseProperties err = json.Unmarshal(*v, &recoverableManagedDatabaseProperties) if err != nil { return err } rmd.RecoverableManagedDatabaseProperties = &recoverableManagedDatabaseProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } rmd.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } rmd.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } rmd.Type = &typeVar } } } return nil } // RecoverableManagedDatabaseListResult a list of recoverable managed databases. type RecoverableManagedDatabaseListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]RecoverableManagedDatabase `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // RecoverableManagedDatabaseListResultIterator provides access to a complete listing of // RecoverableManagedDatabase values. type RecoverableManagedDatabaseListResultIterator struct { i int page RecoverableManagedDatabaseListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *RecoverableManagedDatabaseListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/RecoverableManagedDatabaseListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *RecoverableManagedDatabaseListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter RecoverableManagedDatabaseListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter RecoverableManagedDatabaseListResultIterator) Response() RecoverableManagedDatabaseListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter RecoverableManagedDatabaseListResultIterator) Value() RecoverableManagedDatabase { if !iter.page.NotDone() { return RecoverableManagedDatabase{} } return iter.page.Values()[iter.i] } // Creates a new instance of the RecoverableManagedDatabaseListResultIterator type. func NewRecoverableManagedDatabaseListResultIterator(page RecoverableManagedDatabaseListResultPage) RecoverableManagedDatabaseListResultIterator { return RecoverableManagedDatabaseListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (rmdlr RecoverableManagedDatabaseListResult) IsEmpty() bool { return rmdlr.Value == nil || len(*rmdlr.Value) == 0 } // recoverableManagedDatabaseListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (rmdlr RecoverableManagedDatabaseListResult) recoverableManagedDatabaseListResultPreparer(ctx context.Context) (*http.Request, error) { if rmdlr.NextLink == nil || len(to.String(rmdlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(rmdlr.NextLink))) } // RecoverableManagedDatabaseListResultPage contains a page of RecoverableManagedDatabase values. type RecoverableManagedDatabaseListResultPage struct { fn func(context.Context, RecoverableManagedDatabaseListResult) (RecoverableManagedDatabaseListResult, error) rmdlr RecoverableManagedDatabaseListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *RecoverableManagedDatabaseListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/RecoverableManagedDatabaseListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.rmdlr) if err != nil { return err } page.rmdlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *RecoverableManagedDatabaseListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page RecoverableManagedDatabaseListResultPage) NotDone() bool { return !page.rmdlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page RecoverableManagedDatabaseListResultPage) Response() RecoverableManagedDatabaseListResult { return page.rmdlr } // Values returns the slice of values for the current page or nil if there are no values. func (page RecoverableManagedDatabaseListResultPage) Values() []RecoverableManagedDatabase { if page.rmdlr.IsEmpty() { return nil } return *page.rmdlr.Value } // Creates a new instance of the RecoverableManagedDatabaseListResultPage type. func NewRecoverableManagedDatabaseListResultPage(getNextPage func(context.Context, RecoverableManagedDatabaseListResult) (RecoverableManagedDatabaseListResult, error)) RecoverableManagedDatabaseListResultPage { return RecoverableManagedDatabaseListResultPage{fn: getNextPage} } // RecoverableManagedDatabaseProperties the recoverable managed database's properties. type RecoverableManagedDatabaseProperties struct { // LastAvailableBackupDate - READ-ONLY; The last available backup date. LastAvailableBackupDate *string `json:"lastAvailableBackupDate,omitempty"` } // ReplicationLink represents a database replication link. type ReplicationLink struct { autorest.Response `json:"-"` // Location - READ-ONLY; Location of the server that contains this firewall rule. Location *string `json:"location,omitempty"` // ReplicationLinkProperties - The properties representing the resource. *ReplicationLinkProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ReplicationLink. func (rl ReplicationLink) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if rl.ReplicationLinkProperties != nil { objectMap["properties"] = rl.ReplicationLinkProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ReplicationLink struct. func (rl *ReplicationLink) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } rl.Location = &location } case "properties": if v != nil { var replicationLinkProperties ReplicationLinkProperties err = json.Unmarshal(*v, &replicationLinkProperties) if err != nil { return err } rl.ReplicationLinkProperties = &replicationLinkProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } rl.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } rl.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } rl.Type = &typeVar } } } return nil } // ReplicationLinkListResult represents the response to a List database replication link request. type ReplicationLinkListResult struct { autorest.Response `json:"-"` // Value - The list of database replication links housed in the database. Value *[]ReplicationLink `json:"value,omitempty"` } // ReplicationLinkProperties represents the properties of a database replication link. type ReplicationLinkProperties struct { // IsTerminationAllowed - READ-ONLY; Legacy value indicating whether termination is allowed. Currently always returns true. IsTerminationAllowed *bool `json:"isTerminationAllowed,omitempty"` // ReplicationMode - READ-ONLY; Replication mode of this replication link. ReplicationMode *string `json:"replicationMode,omitempty"` // PartnerServer - READ-ONLY; The name of the server hosting the partner database. PartnerServer *string `json:"partnerServer,omitempty"` // PartnerDatabase - READ-ONLY; The name of the partner database. PartnerDatabase *string `json:"partnerDatabase,omitempty"` // PartnerLocation - READ-ONLY; The Azure Region of the partner database. PartnerLocation *string `json:"partnerLocation,omitempty"` // Role - READ-ONLY; The role of the database in the replication link. Possible values include: 'ReplicationRolePrimary', 'ReplicationRoleSecondary', 'ReplicationRoleNonReadableSecondary', 'ReplicationRoleSource', 'ReplicationRoleCopy' Role ReplicationRole `json:"role,omitempty"` // PartnerRole - READ-ONLY; The role of the partner database in the replication link. Possible values include: 'ReplicationRolePrimary', 'ReplicationRoleSecondary', 'ReplicationRoleNonReadableSecondary', 'ReplicationRoleSource', 'ReplicationRoleCopy' PartnerRole ReplicationRole `json:"partnerRole,omitempty"` // StartTime - READ-ONLY; The start time for the replication link. StartTime *date.Time `json:"startTime,omitempty"` // PercentComplete - READ-ONLY; The percentage of seeding complete for the replication link. PercentComplete *int32 `json:"percentComplete,omitempty"` // ReplicationState - READ-ONLY; The replication state for the replication link. Possible values include: 'PENDING', 'SEEDING', 'CATCHUP', 'SUSPENDED' ReplicationState ReplicationState `json:"replicationState,omitempty"` } // ReplicationLinksFailoverAllowDataLossFuture an abstraction for monitoring and retrieving the results of // a long-running operation. type ReplicationLinksFailoverAllowDataLossFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ReplicationLinksFailoverAllowDataLossFuture) Result(client ReplicationLinksClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ReplicationLinksFailoverAllowDataLossFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ReplicationLinksFailoverAllowDataLossFuture") return } ar.Response = future.Response() return } // ReplicationLinksFailoverFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ReplicationLinksFailoverFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ReplicationLinksFailoverFuture) Result(client ReplicationLinksClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ReplicationLinksFailoverFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ReplicationLinksFailoverFuture") return } ar.Response = future.Response() return } // Resource ARM resource. type Resource struct { // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // ResourceIdentity azure Active Directory identity configuration for a resource. type ResourceIdentity struct { // PrincipalID - READ-ONLY; The Azure Active Directory principal id. PrincipalID *uuid.UUID `json:"principalId,omitempty"` // 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 IdentityType `json:"type,omitempty"` // TenantID - READ-ONLY; The Azure Active Directory tenant id. TenantID *uuid.UUID `json:"tenantId,omitempty"` } // ResourceMoveDefinition contains the information necessary to perform a resource move (rename). type ResourceMoveDefinition struct { // ID - The target ID for the resource ID *string `json:"id,omitempty"` } // RestorableDroppedDatabase a restorable dropped database type RestorableDroppedDatabase struct { autorest.Response `json:"-"` // Location - READ-ONLY; The geo-location where the resource lives Location *string `json:"location,omitempty"` // RestorableDroppedDatabaseProperties - The properties of a restorable dropped database *RestorableDroppedDatabaseProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for RestorableDroppedDatabase. func (rdd RestorableDroppedDatabase) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if rdd.RestorableDroppedDatabaseProperties != nil { objectMap["properties"] = rdd.RestorableDroppedDatabaseProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for RestorableDroppedDatabase struct. func (rdd *RestorableDroppedDatabase) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } rdd.Location = &location } case "properties": if v != nil { var restorableDroppedDatabaseProperties RestorableDroppedDatabaseProperties err = json.Unmarshal(*v, &restorableDroppedDatabaseProperties) if err != nil { return err } rdd.RestorableDroppedDatabaseProperties = &restorableDroppedDatabaseProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } rdd.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } rdd.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } rdd.Type = &typeVar } } } return nil } // RestorableDroppedDatabaseListResult the response to a list restorable dropped databases request type RestorableDroppedDatabaseListResult struct { autorest.Response `json:"-"` // Value - A list of restorable dropped databases Value *[]RestorableDroppedDatabase `json:"value,omitempty"` } // RestorableDroppedDatabaseProperties the properties of a restorable dropped database type RestorableDroppedDatabaseProperties struct { // DatabaseName - READ-ONLY; The name of the database DatabaseName *string `json:"databaseName,omitempty"` // Edition - READ-ONLY; The edition of the database Edition *string `json:"edition,omitempty"` // MaxSizeBytes - READ-ONLY; The max size in bytes of the database MaxSizeBytes *string `json:"maxSizeBytes,omitempty"` // ServiceLevelObjective - READ-ONLY; The service level objective name of the database ServiceLevelObjective *string `json:"serviceLevelObjective,omitempty"` // ElasticPoolName - READ-ONLY; The elastic pool name of the database ElasticPoolName *string `json:"elasticPoolName,omitempty"` // CreationDate - READ-ONLY; The creation date of the database (ISO8601 format) CreationDate *date.Time `json:"creationDate,omitempty"` // DeletionDate - READ-ONLY; The deletion date of the database (ISO8601 format) DeletionDate *date.Time `json:"deletionDate,omitempty"` // EarliestRestoreDate - READ-ONLY; The earliest restore date of the database (ISO8601 format) EarliestRestoreDate *date.Time `json:"earliestRestoreDate,omitempty"` } // RestorableDroppedManagedDatabase a restorable dropped managed database resource. type RestorableDroppedManagedDatabase struct { autorest.Response `json:"-"` // RestorableDroppedManagedDatabaseProperties - Resource properties. *RestorableDroppedManagedDatabaseProperties `json:"properties,omitempty"` // Location - Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for RestorableDroppedManagedDatabase. func (rdmd RestorableDroppedManagedDatabase) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if rdmd.RestorableDroppedManagedDatabaseProperties != nil { objectMap["properties"] = rdmd.RestorableDroppedManagedDatabaseProperties } if rdmd.Location != nil { objectMap["location"] = rdmd.Location } if rdmd.Tags != nil { objectMap["tags"] = rdmd.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for RestorableDroppedManagedDatabase struct. func (rdmd *RestorableDroppedManagedDatabase) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var restorableDroppedManagedDatabaseProperties RestorableDroppedManagedDatabaseProperties err = json.Unmarshal(*v, &restorableDroppedManagedDatabaseProperties) if err != nil { return err } rdmd.RestorableDroppedManagedDatabaseProperties = &restorableDroppedManagedDatabaseProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } rdmd.Location = &location } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } rdmd.Tags = tags } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } rdmd.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } rdmd.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } rdmd.Type = &typeVar } } } return nil } // RestorableDroppedManagedDatabaseListResult a list of restorable dropped managed databases. type RestorableDroppedManagedDatabaseListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]RestorableDroppedManagedDatabase `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // RestorableDroppedManagedDatabaseListResultIterator provides access to a complete listing of // RestorableDroppedManagedDatabase values. type RestorableDroppedManagedDatabaseListResultIterator struct { i int page RestorableDroppedManagedDatabaseListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *RestorableDroppedManagedDatabaseListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/RestorableDroppedManagedDatabaseListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *RestorableDroppedManagedDatabaseListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter RestorableDroppedManagedDatabaseListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter RestorableDroppedManagedDatabaseListResultIterator) Response() RestorableDroppedManagedDatabaseListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter RestorableDroppedManagedDatabaseListResultIterator) Value() RestorableDroppedManagedDatabase { if !iter.page.NotDone() { return RestorableDroppedManagedDatabase{} } return iter.page.Values()[iter.i] } // Creates a new instance of the RestorableDroppedManagedDatabaseListResultIterator type. func NewRestorableDroppedManagedDatabaseListResultIterator(page RestorableDroppedManagedDatabaseListResultPage) RestorableDroppedManagedDatabaseListResultIterator { return RestorableDroppedManagedDatabaseListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (rdmdlr RestorableDroppedManagedDatabaseListResult) IsEmpty() bool { return rdmdlr.Value == nil || len(*rdmdlr.Value) == 0 } // restorableDroppedManagedDatabaseListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (rdmdlr RestorableDroppedManagedDatabaseListResult) restorableDroppedManagedDatabaseListResultPreparer(ctx context.Context) (*http.Request, error) { if rdmdlr.NextLink == nil || len(to.String(rdmdlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(rdmdlr.NextLink))) } // RestorableDroppedManagedDatabaseListResultPage contains a page of RestorableDroppedManagedDatabase // values. type RestorableDroppedManagedDatabaseListResultPage struct { fn func(context.Context, RestorableDroppedManagedDatabaseListResult) (RestorableDroppedManagedDatabaseListResult, error) rdmdlr RestorableDroppedManagedDatabaseListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *RestorableDroppedManagedDatabaseListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/RestorableDroppedManagedDatabaseListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.rdmdlr) if err != nil { return err } page.rdmdlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *RestorableDroppedManagedDatabaseListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page RestorableDroppedManagedDatabaseListResultPage) NotDone() bool { return !page.rdmdlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page RestorableDroppedManagedDatabaseListResultPage) Response() RestorableDroppedManagedDatabaseListResult { return page.rdmdlr } // Values returns the slice of values for the current page or nil if there are no values. func (page RestorableDroppedManagedDatabaseListResultPage) Values() []RestorableDroppedManagedDatabase { if page.rdmdlr.IsEmpty() { return nil } return *page.rdmdlr.Value } // Creates a new instance of the RestorableDroppedManagedDatabaseListResultPage type. func NewRestorableDroppedManagedDatabaseListResultPage(getNextPage func(context.Context, RestorableDroppedManagedDatabaseListResult) (RestorableDroppedManagedDatabaseListResult, error)) RestorableDroppedManagedDatabaseListResultPage { return RestorableDroppedManagedDatabaseListResultPage{fn: getNextPage} } // RestorableDroppedManagedDatabaseProperties the restorable dropped managed database's properties. type RestorableDroppedManagedDatabaseProperties struct { // DatabaseName - READ-ONLY; The name of the database. DatabaseName *string `json:"databaseName,omitempty"` // CreationDate - READ-ONLY; The creation date of the database (ISO8601 format). CreationDate *date.Time `json:"creationDate,omitempty"` // DeletionDate - READ-ONLY; The deletion date of the database (ISO8601 format). DeletionDate *date.Time `json:"deletionDate,omitempty"` // EarliestRestoreDate - READ-ONLY; The earliest restore date of the database (ISO8601 format). EarliestRestoreDate *date.Time `json:"earliestRestoreDate,omitempty"` } // RestorePoint database restore points. type RestorePoint struct { autorest.Response `json:"-"` // Location - READ-ONLY; Resource location. Location *string `json:"location,omitempty"` // RestorePointProperties - Resource properties. *RestorePointProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for RestorePoint. func (rp RestorePoint) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if rp.RestorePointProperties != nil { objectMap["properties"] = rp.RestorePointProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for RestorePoint struct. func (rp *RestorePoint) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } rp.Location = &location } case "properties": if v != nil { var restorePointProperties RestorePointProperties err = json.Unmarshal(*v, &restorePointProperties) if err != nil { return err } rp.RestorePointProperties = &restorePointProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } rp.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } rp.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } rp.Type = &typeVar } } } return nil } // RestorePointListResult a list of long term retention backups. type RestorePointListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]RestorePoint `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // RestorePointProperties properties of a database restore point type RestorePointProperties struct { // RestorePointType - READ-ONLY; The type of restore point. Possible values include: 'CONTINUOUS', 'DISCRETE' RestorePointType RestorePointType `json:"restorePointType,omitempty"` // EarliestRestoreDate - READ-ONLY; The earliest time to which this database can be restored EarliestRestoreDate *date.Time `json:"earliestRestoreDate,omitempty"` // RestorePointCreationDate - READ-ONLY; The time the backup was taken RestorePointCreationDate *date.Time `json:"restorePointCreationDate,omitempty"` // RestorePointLabel - READ-ONLY; The label of restore point for backup request by user RestorePointLabel *string `json:"restorePointLabel,omitempty"` } // RestorePointsCreateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type RestorePointsCreateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *RestorePointsCreateFuture) Result(client RestorePointsClient) (rp RestorePoint, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.RestorePointsCreateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.RestorePointsCreateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if rp.Response.Response, err = future.GetResult(sender); err == nil && rp.Response.Response.StatusCode != http.StatusNoContent { rp, err = client.CreateResponder(rp.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.RestorePointsCreateFuture", "Result", rp.Response.Response, "Failure responding to request") } } return } // SecurityAlertPolicyProperties properties of a security alert policy. type SecurityAlertPolicyProperties struct { // State - Specifies the state of the policy, whether it is enabled or disabled or a policy has not been applied yet on the specific database. Possible values include: 'SecurityAlertPolicyStateNew', 'SecurityAlertPolicyStateEnabled', 'SecurityAlertPolicyStateDisabled' State SecurityAlertPolicyState `json:"state,omitempty"` // DisabledAlerts - Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly, Data_Exfiltration, Unsafe_Action DisabledAlerts *[]string `json:"disabledAlerts,omitempty"` // EmailAddresses - Specifies an array of e-mail addresses to which the alert is sent. EmailAddresses *[]string `json:"emailAddresses,omitempty"` // EmailAccountAdmins - Specifies that the alert is sent to the account administrators. EmailAccountAdmins *bool `json:"emailAccountAdmins,omitempty"` // StorageEndpoint - Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection audit logs. StorageEndpoint *string `json:"storageEndpoint,omitempty"` // StorageAccountAccessKey - Specifies the identifier key of the Threat Detection audit storage account. StorageAccountAccessKey *string `json:"storageAccountAccessKey,omitempty"` // RetentionDays - Specifies the number of days to keep in the Threat Detection audit logs. RetentionDays *int32 `json:"retentionDays,omitempty"` // CreationTime - READ-ONLY; Specifies the UTC creation time of the policy. CreationTime *date.Time `json:"creationTime,omitempty"` } // SensitivityLabel a sensitivity label. type SensitivityLabel struct { autorest.Response `json:"-"` // SensitivityLabelProperties - Resource properties. *SensitivityLabelProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for SensitivityLabel. func (sl SensitivityLabel) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if sl.SensitivityLabelProperties != nil { objectMap["properties"] = sl.SensitivityLabelProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for SensitivityLabel struct. func (sl *SensitivityLabel) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var sensitivityLabelProperties SensitivityLabelProperties err = json.Unmarshal(*v, &sensitivityLabelProperties) if err != nil { return err } sl.SensitivityLabelProperties = &sensitivityLabelProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sl.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sl.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sl.Type = &typeVar } } } return nil } // SensitivityLabelListResult a list of sensitivity labels. type SensitivityLabelListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]SensitivityLabel `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // SensitivityLabelListResultIterator provides access to a complete listing of SensitivityLabel values. type SensitivityLabelListResultIterator struct { i int page SensitivityLabelListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *SensitivityLabelListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SensitivityLabelListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *SensitivityLabelListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter SensitivityLabelListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter SensitivityLabelListResultIterator) Response() SensitivityLabelListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter SensitivityLabelListResultIterator) Value() SensitivityLabel { if !iter.page.NotDone() { return SensitivityLabel{} } return iter.page.Values()[iter.i] } // Creates a new instance of the SensitivityLabelListResultIterator type. func NewSensitivityLabelListResultIterator(page SensitivityLabelListResultPage) SensitivityLabelListResultIterator { return SensitivityLabelListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (sllr SensitivityLabelListResult) IsEmpty() bool { return sllr.Value == nil || len(*sllr.Value) == 0 } // sensitivityLabelListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (sllr SensitivityLabelListResult) sensitivityLabelListResultPreparer(ctx context.Context) (*http.Request, error) { if sllr.NextLink == nil || len(to.String(sllr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(sllr.NextLink))) } // SensitivityLabelListResultPage contains a page of SensitivityLabel values. type SensitivityLabelListResultPage struct { fn func(context.Context, SensitivityLabelListResult) (SensitivityLabelListResult, error) sllr SensitivityLabelListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *SensitivityLabelListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SensitivityLabelListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.sllr) if err != nil { return err } page.sllr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *SensitivityLabelListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page SensitivityLabelListResultPage) NotDone() bool { return !page.sllr.IsEmpty() } // Response returns the raw server response from the last page request. func (page SensitivityLabelListResultPage) Response() SensitivityLabelListResult { return page.sllr } // Values returns the slice of values for the current page or nil if there are no values. func (page SensitivityLabelListResultPage) Values() []SensitivityLabel { if page.sllr.IsEmpty() { return nil } return *page.sllr.Value } // Creates a new instance of the SensitivityLabelListResultPage type. func NewSensitivityLabelListResultPage(getNextPage func(context.Context, SensitivityLabelListResult) (SensitivityLabelListResult, error)) SensitivityLabelListResultPage { return SensitivityLabelListResultPage{fn: getNextPage} } // SensitivityLabelProperties properties of a sensitivity label. type SensitivityLabelProperties struct { // LabelName - The label name. LabelName *string `json:"labelName,omitempty"` // LabelID - The label ID. LabelID *string `json:"labelId,omitempty"` // InformationType - The information type. InformationType *string `json:"informationType,omitempty"` // InformationTypeID - The information type ID. InformationTypeID *string `json:"informationTypeId,omitempty"` // IsDisabled - READ-ONLY; Is sensitivity recommendation disabled. Applicable for recommended sensitivity label only. Specifies whether the sensitivity recommendation on this column is disabled (dismissed) or not. IsDisabled *bool `json:"isDisabled,omitempty"` } // Server an Azure SQL Database server. type Server struct { autorest.Response `json:"-"` // Identity - The Azure Active Directory identity of the server. Identity *ResourceIdentity `json:"identity,omitempty"` // Kind - READ-ONLY; Kind of sql server. This is metadata used for the Azure portal experience. Kind *string `json:"kind,omitempty"` // ServerProperties - Resource properties. *ServerProperties `json:"properties,omitempty"` // Location - Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for Server. func (s Server) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if s.Identity != nil { objectMap["identity"] = s.Identity } if s.ServerProperties != nil { objectMap["properties"] = s.ServerProperties } if s.Location != nil { objectMap["location"] = s.Location } if s.Tags != nil { objectMap["tags"] = s.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for Server struct. func (s *Server) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "identity": if v != nil { var identity ResourceIdentity err = json.Unmarshal(*v, &identity) if err != nil { return err } s.Identity = &identity } case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } s.Kind = &kind } case "properties": if v != nil { var serverProperties ServerProperties err = json.Unmarshal(*v, &serverProperties) if err != nil { return err } s.ServerProperties = &serverProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } s.Location = &location } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } s.Tags = tags } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } s.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } s.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } s.Type = &typeVar } } } return nil } // ServerAdministratorListResult the response to a list Active Directory Administrators request. type ServerAdministratorListResult struct { autorest.Response `json:"-"` // Value - The list of server Active Directory Administrators for the server. Value *[]ServerAzureADAdministrator `json:"value,omitempty"` } // ServerAdministratorProperties the properties of an server Administrator. type ServerAdministratorProperties struct { // AdministratorType - The type of administrator. AdministratorType *string `json:"administratorType,omitempty"` // Login - The server administrator login value. Login *string `json:"login,omitempty"` // Sid - The server administrator Sid (Secure ID). Sid *uuid.UUID `json:"sid,omitempty"` // TenantID - The server Active Directory Administrator tenant id. TenantID *uuid.UUID `json:"tenantId,omitempty"` } // ServerAutomaticTuning server-level Automatic Tuning. type ServerAutomaticTuning struct { autorest.Response `json:"-"` // AutomaticTuningServerProperties - Resource properties. *AutomaticTuningServerProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServerAutomaticTuning. func (sat ServerAutomaticTuning) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if sat.AutomaticTuningServerProperties != nil { objectMap["properties"] = sat.AutomaticTuningServerProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServerAutomaticTuning struct. func (sat *ServerAutomaticTuning) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var automaticTuningServerProperties AutomaticTuningServerProperties err = json.Unmarshal(*v, &automaticTuningServerProperties) if err != nil { return err } sat.AutomaticTuningServerProperties = &automaticTuningServerProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sat.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sat.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sat.Type = &typeVar } } } return nil } // ServerAzureADAdministrator an server Active Directory Administrator. type ServerAzureADAdministrator struct { autorest.Response `json:"-"` // ServerAdministratorProperties - The properties of the resource. *ServerAdministratorProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServerAzureADAdministrator. func (saaa ServerAzureADAdministrator) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if saaa.ServerAdministratorProperties != nil { objectMap["properties"] = saaa.ServerAdministratorProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServerAzureADAdministrator struct. func (saaa *ServerAzureADAdministrator) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var serverAdministratorProperties ServerAdministratorProperties err = json.Unmarshal(*v, &serverAdministratorProperties) if err != nil { return err } saaa.ServerAdministratorProperties = &serverAdministratorProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } saaa.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } saaa.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } saaa.Type = &typeVar } } } return nil } // ServerAzureADAdministratorsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results // of a long-running operation. type ServerAzureADAdministratorsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServerAzureADAdministratorsCreateOrUpdateFuture) Result(client ServerAzureADAdministratorsClient) (saaa ServerAzureADAdministrator, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerAzureADAdministratorsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServerAzureADAdministratorsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if saaa.Response.Response, err = future.GetResult(sender); err == nil && saaa.Response.Response.StatusCode != http.StatusNoContent { saaa, err = client.CreateOrUpdateResponder(saaa.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerAzureADAdministratorsCreateOrUpdateFuture", "Result", saaa.Response.Response, "Failure responding to request") } } return } // ServerAzureADAdministratorsDeleteFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ServerAzureADAdministratorsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServerAzureADAdministratorsDeleteFuture) Result(client ServerAzureADAdministratorsClient) (saaa ServerAzureADAdministrator, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerAzureADAdministratorsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServerAzureADAdministratorsDeleteFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if saaa.Response.Response, err = future.GetResult(sender); err == nil && saaa.Response.Response.StatusCode != http.StatusNoContent { saaa, err = client.DeleteResponder(saaa.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerAzureADAdministratorsDeleteFuture", "Result", saaa.Response.Response, "Failure responding to request") } } return } // ServerBlobAuditingPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results // of a long-running operation. type ServerBlobAuditingPoliciesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServerBlobAuditingPoliciesCreateOrUpdateFuture) Result(client ServerBlobAuditingPoliciesClient) (sbap ServerBlobAuditingPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerBlobAuditingPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServerBlobAuditingPoliciesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if sbap.Response.Response, err = future.GetResult(sender); err == nil && sbap.Response.Response.StatusCode != http.StatusNoContent { sbap, err = client.CreateOrUpdateResponder(sbap.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerBlobAuditingPoliciesCreateOrUpdateFuture", "Result", sbap.Response.Response, "Failure responding to request") } } return } // ServerBlobAuditingPolicy a server blob auditing policy. type ServerBlobAuditingPolicy struct { autorest.Response `json:"-"` // ServerBlobAuditingPolicyProperties - Resource properties. *ServerBlobAuditingPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServerBlobAuditingPolicy. func (sbap ServerBlobAuditingPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if sbap.ServerBlobAuditingPolicyProperties != nil { objectMap["properties"] = sbap.ServerBlobAuditingPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServerBlobAuditingPolicy struct. func (sbap *ServerBlobAuditingPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var serverBlobAuditingPolicyProperties ServerBlobAuditingPolicyProperties err = json.Unmarshal(*v, &serverBlobAuditingPolicyProperties) if err != nil { return err } sbap.ServerBlobAuditingPolicyProperties = &serverBlobAuditingPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sbap.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sbap.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sbap.Type = &typeVar } } } return nil } // ServerBlobAuditingPolicyListResult a list of server auditing settings. type ServerBlobAuditingPolicyListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ServerBlobAuditingPolicy `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ServerBlobAuditingPolicyListResultIterator provides access to a complete listing of // ServerBlobAuditingPolicy values. type ServerBlobAuditingPolicyListResultIterator struct { i int page ServerBlobAuditingPolicyListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ServerBlobAuditingPolicyListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServerBlobAuditingPolicyListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ServerBlobAuditingPolicyListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ServerBlobAuditingPolicyListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ServerBlobAuditingPolicyListResultIterator) Response() ServerBlobAuditingPolicyListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ServerBlobAuditingPolicyListResultIterator) Value() ServerBlobAuditingPolicy { if !iter.page.NotDone() { return ServerBlobAuditingPolicy{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ServerBlobAuditingPolicyListResultIterator type. func NewServerBlobAuditingPolicyListResultIterator(page ServerBlobAuditingPolicyListResultPage) ServerBlobAuditingPolicyListResultIterator { return ServerBlobAuditingPolicyListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (sbaplr ServerBlobAuditingPolicyListResult) IsEmpty() bool { return sbaplr.Value == nil || len(*sbaplr.Value) == 0 } // serverBlobAuditingPolicyListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (sbaplr ServerBlobAuditingPolicyListResult) serverBlobAuditingPolicyListResultPreparer(ctx context.Context) (*http.Request, error) { if sbaplr.NextLink == nil || len(to.String(sbaplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(sbaplr.NextLink))) } // ServerBlobAuditingPolicyListResultPage contains a page of ServerBlobAuditingPolicy values. type ServerBlobAuditingPolicyListResultPage struct { fn func(context.Context, ServerBlobAuditingPolicyListResult) (ServerBlobAuditingPolicyListResult, error) sbaplr ServerBlobAuditingPolicyListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ServerBlobAuditingPolicyListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServerBlobAuditingPolicyListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.sbaplr) if err != nil { return err } page.sbaplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ServerBlobAuditingPolicyListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ServerBlobAuditingPolicyListResultPage) NotDone() bool { return !page.sbaplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ServerBlobAuditingPolicyListResultPage) Response() ServerBlobAuditingPolicyListResult { return page.sbaplr } // Values returns the slice of values for the current page or nil if there are no values. func (page ServerBlobAuditingPolicyListResultPage) Values() []ServerBlobAuditingPolicy { if page.sbaplr.IsEmpty() { return nil } return *page.sbaplr.Value } // Creates a new instance of the ServerBlobAuditingPolicyListResultPage type. func NewServerBlobAuditingPolicyListResultPage(getNextPage func(context.Context, ServerBlobAuditingPolicyListResult) (ServerBlobAuditingPolicyListResult, error)) ServerBlobAuditingPolicyListResultPage { return ServerBlobAuditingPolicyListResultPage{fn: getNextPage} } // ServerBlobAuditingPolicyProperties properties of a server blob auditing policy. type ServerBlobAuditingPolicyProperties struct { // State - Specifies the state of the policy. If state is Enabled, storageEndpoint or isAzureMonitorTargetEnabled are required. Possible values include: 'BlobAuditingPolicyStateEnabled', 'BlobAuditingPolicyStateDisabled' State BlobAuditingPolicyState `json:"state,omitempty"` // StorageEndpoint - Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). If state is Enabled, storageEndpoint is required. StorageEndpoint *string `json:"storageEndpoint,omitempty"` // StorageAccountAccessKey - Specifies the identifier key of the auditing storage account. If state is Enabled and storageEndpoint is specified, storageAccountAccessKey is required. StorageAccountAccessKey *string `json:"storageAccountAccessKey,omitempty"` // RetentionDays - Specifies the number of days to keep in the audit logs in the storage account. RetentionDays *int32 `json:"retentionDays,omitempty"` // AuditActionsAndGroups - Specifies the Actions-Groups and Actions to audit. // // The recommended set of action groups to use is the following combination - this will audit all the queries and stored procedures executed against the database, as well as successful and failed logins: // // BATCH_COMPLETED_GROUP, // SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP, // FAILED_DATABASE_AUTHENTICATION_GROUP. // // This above combination is also the set that is configured by default when enabling auditing from the Azure portal. // // The supported action groups to audit are (note: choose only specific groups that cover your auditing needs. Using unnecessary groups could lead to very large quantities of audit records): // // APPLICATION_ROLE_CHANGE_PASSWORD_GROUP // BACKUP_RESTORE_GROUP // DATABASE_LOGOUT_GROUP // DATABASE_OBJECT_CHANGE_GROUP // DATABASE_OBJECT_OWNERSHIP_CHANGE_GROUP // DATABASE_OBJECT_PERMISSION_CHANGE_GROUP // DATABASE_OPERATION_GROUP // DATABASE_PERMISSION_CHANGE_GROUP // DATABASE_PRINCIPAL_CHANGE_GROUP // DATABASE_PRINCIPAL_IMPERSONATION_GROUP // DATABASE_ROLE_MEMBER_CHANGE_GROUP // FAILED_DATABASE_AUTHENTICATION_GROUP // SCHEMA_OBJECT_ACCESS_GROUP // SCHEMA_OBJECT_CHANGE_GROUP // SCHEMA_OBJECT_OWNERSHIP_CHANGE_GROUP // SCHEMA_OBJECT_PERMISSION_CHANGE_GROUP // SUCCESSFUL_DATABASE_AUTHENTICATION_GROUP // USER_CHANGE_PASSWORD_GROUP // BATCH_STARTED_GROUP // BATCH_COMPLETED_GROUP // // These are groups that cover all sql statements and stored procedures executed against the database, and should not be used in combination with other groups as this will result in duplicate audit logs. // // For more information, see [Database-Level Audit Action Groups](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-action-groups). // // For Database auditing policy, specific Actions can also be specified (note that Actions cannot be specified for Server auditing policy). The supported actions to audit are: // SELECT // UPDATE // INSERT // DELETE // EXECUTE // RECEIVE // REFERENCES // // The general form for defining an action to be audited is: // {action} ON {object} BY {principal} // // Note that <object> in the above format can refer to an object like a table, view, or stored procedure, or an entire database or schema. For the latter cases, the forms DATABASE::{db_name} and SCHEMA::{schema_name} are used, respectively. // // For example: // SELECT on dbo.myTable by public // SELECT on DATABASE::myDatabase by public // SELECT on SCHEMA::mySchema by public // // For more information, see [Database-Level Audit Actions](https://docs.microsoft.com/en-us/sql/relational-databases/security/auditing/sql-server-audit-action-groups-and-actions#database-level-audit-actions) AuditActionsAndGroups *[]string `json:"auditActionsAndGroups,omitempty"` // StorageAccountSubscriptionID - Specifies the blob storage subscription Id. StorageAccountSubscriptionID *uuid.UUID `json:"storageAccountSubscriptionId,omitempty"` // IsStorageSecondaryKeyInUse - Specifies whether storageAccountAccessKey value is the storage's secondary key. IsStorageSecondaryKeyInUse *bool `json:"isStorageSecondaryKeyInUse,omitempty"` // IsAzureMonitorTargetEnabled - Specifies whether audit events are sent to Azure Monitor. // In order to send the events to Azure Monitor, specify 'state' as 'Enabled' and 'isAzureMonitorTargetEnabled' as true. // // When using REST API to configure auditing, Diagnostic Settings with 'SQLSecurityAuditEvents' diagnostic logs category on the database should be also created. // Note that for server level audit you should use the 'master' database as {databaseName}. // // Diagnostic Settings URI format: // PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/providers/microsoft.insights/diagnosticSettings/{settingsName}?api-version=2017-05-01-preview // // For more information, see [Diagnostic Settings REST API](https://go.microsoft.com/fwlink/?linkid=2033207) // or [Diagnostic Settings PowerShell](https://go.microsoft.com/fwlink/?linkid=2033043) IsAzureMonitorTargetEnabled *bool `json:"isAzureMonitorTargetEnabled,omitempty"` } // ServerCommunicationLink server communication link. type ServerCommunicationLink struct { autorest.Response `json:"-"` // ServerCommunicationLinkProperties - The properties of resource. *ServerCommunicationLinkProperties `json:"properties,omitempty"` // Location - READ-ONLY; Communication link location. Location *string `json:"location,omitempty"` // Kind - READ-ONLY; Communication link kind. This property is used for Azure Portal metadata. Kind *string `json:"kind,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServerCommunicationLink. func (scl ServerCommunicationLink) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if scl.ServerCommunicationLinkProperties != nil { objectMap["properties"] = scl.ServerCommunicationLinkProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServerCommunicationLink struct. func (scl *ServerCommunicationLink) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var serverCommunicationLinkProperties ServerCommunicationLinkProperties err = json.Unmarshal(*v, &serverCommunicationLinkProperties) if err != nil { return err } scl.ServerCommunicationLinkProperties = &serverCommunicationLinkProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } scl.Location = &location } case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } scl.Kind = &kind } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } scl.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } scl.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } scl.Type = &typeVar } } } return nil } // ServerCommunicationLinkListResult a list of server communication links. type ServerCommunicationLinkListResult struct { autorest.Response `json:"-"` // Value - The list of server communication links. Value *[]ServerCommunicationLink `json:"value,omitempty"` } // ServerCommunicationLinkProperties the properties of a server communication link. type ServerCommunicationLinkProperties struct { // State - READ-ONLY; The state. State *string `json:"state,omitempty"` // PartnerServer - The name of the partner server. PartnerServer *string `json:"partnerServer,omitempty"` } // ServerCommunicationLinksCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of // a long-running operation. type ServerCommunicationLinksCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServerCommunicationLinksCreateOrUpdateFuture) Result(client ServerCommunicationLinksClient) (scl ServerCommunicationLink, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerCommunicationLinksCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServerCommunicationLinksCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if scl.Response.Response, err = future.GetResult(sender); err == nil && scl.Response.Response.StatusCode != http.StatusNoContent { scl, err = client.CreateOrUpdateResponder(scl.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerCommunicationLinksCreateOrUpdateFuture", "Result", scl.Response.Response, "Failure responding to request") } } return } // ServerConnectionPolicy a server secure connection policy. type ServerConnectionPolicy struct { autorest.Response `json:"-"` // Kind - READ-ONLY; Metadata used for the Azure portal experience. Kind *string `json:"kind,omitempty"` // Location - READ-ONLY; Resource location. Location *string `json:"location,omitempty"` // ServerConnectionPolicyProperties - The properties of the server secure connection policy. *ServerConnectionPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServerConnectionPolicy. func (scp ServerConnectionPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if scp.ServerConnectionPolicyProperties != nil { objectMap["properties"] = scp.ServerConnectionPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServerConnectionPolicy struct. func (scp *ServerConnectionPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } scp.Kind = &kind } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } scp.Location = &location } case "properties": if v != nil { var serverConnectionPolicyProperties ServerConnectionPolicyProperties err = json.Unmarshal(*v, &serverConnectionPolicyProperties) if err != nil { return err } scp.ServerConnectionPolicyProperties = &serverConnectionPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } scp.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } scp.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } scp.Type = &typeVar } } } return nil } // ServerConnectionPolicyProperties the properties of a server secure connection policy. type ServerConnectionPolicyProperties struct { // ConnectionType - The server connection type. Possible values include: 'ServerConnectionTypeDefault', 'ServerConnectionTypeProxy', 'ServerConnectionTypeRedirect' ConnectionType ServerConnectionType `json:"connectionType,omitempty"` } // ServerDNSAlias a server DNS alias. type ServerDNSAlias struct { autorest.Response `json:"-"` // ServerDNSAliasProperties - Resource properties. *ServerDNSAliasProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServerDNSAlias. func (sda ServerDNSAlias) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if sda.ServerDNSAliasProperties != nil { objectMap["properties"] = sda.ServerDNSAliasProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServerDNSAlias struct. func (sda *ServerDNSAlias) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var serverDNSAliasProperties ServerDNSAliasProperties err = json.Unmarshal(*v, &serverDNSAliasProperties) if err != nil { return err } sda.ServerDNSAliasProperties = &serverDNSAliasProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sda.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sda.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sda.Type = &typeVar } } } return nil } // ServerDNSAliasAcquisition a server DNS alias acquisition request. type ServerDNSAliasAcquisition struct { // OldServerDNSAliasID - The id of the server alias that will be acquired to point to this server instead. OldServerDNSAliasID *string `json:"oldServerDnsAliasId,omitempty"` } // ServerDNSAliasesAcquireFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ServerDNSAliasesAcquireFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServerDNSAliasesAcquireFuture) Result(client ServerDNSAliasesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerDNSAliasesAcquireFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServerDNSAliasesAcquireFuture") return } ar.Response = future.Response() return } // ServerDNSAliasesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ServerDNSAliasesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServerDNSAliasesCreateOrUpdateFuture) Result(client ServerDNSAliasesClient) (sda ServerDNSAlias, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerDNSAliasesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServerDNSAliasesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if sda.Response.Response, err = future.GetResult(sender); err == nil && sda.Response.Response.StatusCode != http.StatusNoContent { sda, err = client.CreateOrUpdateResponder(sda.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerDNSAliasesCreateOrUpdateFuture", "Result", sda.Response.Response, "Failure responding to request") } } return } // ServerDNSAliasesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ServerDNSAliasesDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServerDNSAliasesDeleteFuture) Result(client ServerDNSAliasesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerDNSAliasesDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServerDNSAliasesDeleteFuture") return } ar.Response = future.Response() return } // ServerDNSAliasListResult a list of server DNS aliases. type ServerDNSAliasListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ServerDNSAlias `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ServerDNSAliasListResultIterator provides access to a complete listing of ServerDNSAlias values. type ServerDNSAliasListResultIterator struct { i int page ServerDNSAliasListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ServerDNSAliasListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServerDNSAliasListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ServerDNSAliasListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ServerDNSAliasListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ServerDNSAliasListResultIterator) Response() ServerDNSAliasListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ServerDNSAliasListResultIterator) Value() ServerDNSAlias { if !iter.page.NotDone() { return ServerDNSAlias{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ServerDNSAliasListResultIterator type. func NewServerDNSAliasListResultIterator(page ServerDNSAliasListResultPage) ServerDNSAliasListResultIterator { return ServerDNSAliasListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (sdalr ServerDNSAliasListResult) IsEmpty() bool { return sdalr.Value == nil || len(*sdalr.Value) == 0 } // serverDNSAliasListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (sdalr ServerDNSAliasListResult) serverDNSAliasListResultPreparer(ctx context.Context) (*http.Request, error) { if sdalr.NextLink == nil || len(to.String(sdalr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(sdalr.NextLink))) } // ServerDNSAliasListResultPage contains a page of ServerDNSAlias values. type ServerDNSAliasListResultPage struct { fn func(context.Context, ServerDNSAliasListResult) (ServerDNSAliasListResult, error) sdalr ServerDNSAliasListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ServerDNSAliasListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServerDNSAliasListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.sdalr) if err != nil { return err } page.sdalr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ServerDNSAliasListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ServerDNSAliasListResultPage) NotDone() bool { return !page.sdalr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ServerDNSAliasListResultPage) Response() ServerDNSAliasListResult { return page.sdalr } // Values returns the slice of values for the current page or nil if there are no values. func (page ServerDNSAliasListResultPage) Values() []ServerDNSAlias { if page.sdalr.IsEmpty() { return nil } return *page.sdalr.Value } // Creates a new instance of the ServerDNSAliasListResultPage type. func NewServerDNSAliasListResultPage(getNextPage func(context.Context, ServerDNSAliasListResult) (ServerDNSAliasListResult, error)) ServerDNSAliasListResultPage { return ServerDNSAliasListResultPage{fn: getNextPage} } // ServerDNSAliasProperties properties of a server DNS alias. type ServerDNSAliasProperties struct { // AzureDNSRecord - READ-ONLY; The fully qualified DNS record for alias AzureDNSRecord *string `json:"azureDnsRecord,omitempty"` } // ServerKey a server key. type ServerKey struct { autorest.Response `json:"-"` // Kind - Kind of encryption protector. This is metadata used for the Azure portal experience. Kind *string `json:"kind,omitempty"` // Location - READ-ONLY; Resource location. Location *string `json:"location,omitempty"` // ServerKeyProperties - Resource properties. *ServerKeyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServerKey. func (sk ServerKey) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if sk.Kind != nil { objectMap["kind"] = sk.Kind } if sk.ServerKeyProperties != nil { objectMap["properties"] = sk.ServerKeyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServerKey struct. func (sk *ServerKey) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "kind": if v != nil { var kind string err = json.Unmarshal(*v, &kind) if err != nil { return err } sk.Kind = &kind } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } sk.Location = &location } case "properties": if v != nil { var serverKeyProperties ServerKeyProperties err = json.Unmarshal(*v, &serverKeyProperties) if err != nil { return err } sk.ServerKeyProperties = &serverKeyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sk.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sk.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sk.Type = &typeVar } } } return nil } // ServerKeyListResult a list of server keys. type ServerKeyListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ServerKey `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ServerKeyListResultIterator provides access to a complete listing of ServerKey values. type ServerKeyListResultIterator struct { i int page ServerKeyListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ServerKeyListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServerKeyListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ServerKeyListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ServerKeyListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ServerKeyListResultIterator) Response() ServerKeyListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ServerKeyListResultIterator) Value() ServerKey { if !iter.page.NotDone() { return ServerKey{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ServerKeyListResultIterator type. func NewServerKeyListResultIterator(page ServerKeyListResultPage) ServerKeyListResultIterator { return ServerKeyListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (sklr ServerKeyListResult) IsEmpty() bool { return sklr.Value == nil || len(*sklr.Value) == 0 } // serverKeyListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (sklr ServerKeyListResult) serverKeyListResultPreparer(ctx context.Context) (*http.Request, error) { if sklr.NextLink == nil || len(to.String(sklr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(sklr.NextLink))) } // ServerKeyListResultPage contains a page of ServerKey values. type ServerKeyListResultPage struct { fn func(context.Context, ServerKeyListResult) (ServerKeyListResult, error) sklr ServerKeyListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ServerKeyListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServerKeyListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.sklr) if err != nil { return err } page.sklr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ServerKeyListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ServerKeyListResultPage) NotDone() bool { return !page.sklr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ServerKeyListResultPage) Response() ServerKeyListResult { return page.sklr } // Values returns the slice of values for the current page or nil if there are no values. func (page ServerKeyListResultPage) Values() []ServerKey { if page.sklr.IsEmpty() { return nil } return *page.sklr.Value } // Creates a new instance of the ServerKeyListResultPage type. func NewServerKeyListResultPage(getNextPage func(context.Context, ServerKeyListResult) (ServerKeyListResult, error)) ServerKeyListResultPage { return ServerKeyListResultPage{fn: getNextPage} } // ServerKeyProperties properties for a server key execution. type ServerKeyProperties struct { // Subregion - READ-ONLY; Subregion of the server key. Subregion *string `json:"subregion,omitempty"` // ServerKeyType - The server key type like 'ServiceManaged', 'AzureKeyVault'. Possible values include: 'ServiceManaged', 'AzureKeyVault' ServerKeyType ServerKeyType `json:"serverKeyType,omitempty"` // URI - The URI of the server key. URI *string `json:"uri,omitempty"` // Thumbprint - Thumbprint of the server key. Thumbprint *string `json:"thumbprint,omitempty"` // CreationDate - The server key creation date. CreationDate *date.Time `json:"creationDate,omitempty"` } // ServerKeysCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type ServerKeysCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServerKeysCreateOrUpdateFuture) Result(client ServerKeysClient) (sk ServerKey, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerKeysCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServerKeysCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if sk.Response.Response, err = future.GetResult(sender); err == nil && sk.Response.Response.StatusCode != http.StatusNoContent { sk, err = client.CreateOrUpdateResponder(sk.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerKeysCreateOrUpdateFuture", "Result", sk.Response.Response, "Failure responding to request") } } return } // ServerKeysDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ServerKeysDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServerKeysDeleteFuture) Result(client ServerKeysClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerKeysDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServerKeysDeleteFuture") return } ar.Response = future.Response() return } // ServerListResult a list of servers. type ServerListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]Server `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ServerListResultIterator provides access to a complete listing of Server values. type ServerListResultIterator struct { i int page ServerListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ServerListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServerListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ServerListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ServerListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ServerListResultIterator) Response() ServerListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ServerListResultIterator) Value() Server { if !iter.page.NotDone() { return Server{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ServerListResultIterator type. func NewServerListResultIterator(page ServerListResultPage) ServerListResultIterator { return ServerListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (slr ServerListResult) IsEmpty() bool { return slr.Value == nil || len(*slr.Value) == 0 } // serverListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (slr ServerListResult) serverListResultPreparer(ctx context.Context) (*http.Request, error) { if slr.NextLink == nil || len(to.String(slr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(slr.NextLink))) } // ServerListResultPage contains a page of Server values. type ServerListResultPage struct { fn func(context.Context, ServerListResult) (ServerListResult, error) slr ServerListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ServerListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServerListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.slr) if err != nil { return err } page.slr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ServerListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ServerListResultPage) NotDone() bool { return !page.slr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ServerListResultPage) Response() ServerListResult { return page.slr } // Values returns the slice of values for the current page or nil if there are no values. func (page ServerListResultPage) Values() []Server { if page.slr.IsEmpty() { return nil } return *page.slr.Value } // Creates a new instance of the ServerListResultPage type. func NewServerListResultPage(getNextPage func(context.Context, ServerListResult) (ServerListResult, error)) ServerListResultPage { return ServerListResultPage{fn: getNextPage} } // ServerProperties the properties of a server. type ServerProperties struct { // AdministratorLogin - Administrator username for the server. Once created it cannot be changed. AdministratorLogin *string `json:"administratorLogin,omitempty"` // AdministratorLoginPassword - The administrator login password (required for server creation). AdministratorLoginPassword *string `json:"administratorLoginPassword,omitempty"` // Version - The version of the server. Version *string `json:"version,omitempty"` // State - READ-ONLY; The state of the server. State *string `json:"state,omitempty"` // FullyQualifiedDomainName - READ-ONLY; The fully qualified domain name of the server. FullyQualifiedDomainName *string `json:"fullyQualifiedDomainName,omitempty"` } // ServersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ServersCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServersCreateOrUpdateFuture) Result(client ServersClient) (s Server, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServersCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { s, err = client.CreateOrUpdateResponder(s.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServersCreateOrUpdateFuture", "Result", s.Response.Response, "Failure responding to request") } } return } // ServersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ServersDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServersDeleteFuture) Result(client ServersClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServersDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServersDeleteFuture") return } ar.Response = future.Response() return } // ServerSecurityAlertPoliciesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results // of a long-running operation. type ServerSecurityAlertPoliciesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServerSecurityAlertPoliciesCreateOrUpdateFuture) Result(client ServerSecurityAlertPoliciesClient) (ssap ServerSecurityAlertPolicy, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerSecurityAlertPoliciesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServerSecurityAlertPoliciesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if ssap.Response.Response, err = future.GetResult(sender); err == nil && ssap.Response.Response.StatusCode != http.StatusNoContent { ssap, err = client.CreateOrUpdateResponder(ssap.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServerSecurityAlertPoliciesCreateOrUpdateFuture", "Result", ssap.Response.Response, "Failure responding to request") } } return } // ServerSecurityAlertPolicy a server security alert policy. type ServerSecurityAlertPolicy struct { autorest.Response `json:"-"` // SecurityAlertPolicyProperties - Resource properties. *SecurityAlertPolicyProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServerSecurityAlertPolicy. func (ssap ServerSecurityAlertPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if ssap.SecurityAlertPolicyProperties != nil { objectMap["properties"] = ssap.SecurityAlertPolicyProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServerSecurityAlertPolicy struct. func (ssap *ServerSecurityAlertPolicy) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var securityAlertPolicyProperties SecurityAlertPolicyProperties err = json.Unmarshal(*v, &securityAlertPolicyProperties) if err != nil { return err } ssap.SecurityAlertPolicyProperties = &securityAlertPolicyProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } ssap.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } ssap.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } ssap.Type = &typeVar } } } return nil } // ServersUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type ServersUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *ServersUpdateFuture) Result(client ServersClient) (s Server, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServersUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.ServersUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if s.Response.Response, err = future.GetResult(sender); err == nil && s.Response.Response.StatusCode != http.StatusNoContent { s, err = client.UpdateResponder(s.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.ServersUpdateFuture", "Result", s.Response.Response, "Failure responding to request") } } return } // ServerUpdate an update request for an Azure SQL Database server. type ServerUpdate struct { // ServerProperties - Resource properties. *ServerProperties `json:"properties,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` } // MarshalJSON is the custom marshaler for ServerUpdate. func (su ServerUpdate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if su.ServerProperties != nil { objectMap["properties"] = su.ServerProperties } if su.Tags != nil { objectMap["tags"] = su.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServerUpdate struct. func (su *ServerUpdate) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var serverProperties ServerProperties err = json.Unmarshal(*v, &serverProperties) if err != nil { return err } su.ServerProperties = &serverProperties } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } su.Tags = tags } } } return nil } // ServerUsage represents server metrics. type ServerUsage struct { // Name - READ-ONLY; Name of the server usage metric. Name *string `json:"name,omitempty"` // ResourceName - READ-ONLY; The name of the resource. ResourceName *string `json:"resourceName,omitempty"` // DisplayName - READ-ONLY; The metric display name. DisplayName *string `json:"displayName,omitempty"` // CurrentValue - READ-ONLY; The current value of the metric. CurrentValue *float64 `json:"currentValue,omitempty"` // Limit - READ-ONLY; The current limit of the metric. Limit *float64 `json:"limit,omitempty"` // Unit - READ-ONLY; The units of the metric. Unit *string `json:"unit,omitempty"` // NextResetTime - READ-ONLY; The next reset time for the metric (ISO8601 format). NextResetTime *date.Time `json:"nextResetTime,omitempty"` } // ServerUsageListResult represents the response to a list server metrics request. type ServerUsageListResult struct { autorest.Response `json:"-"` // Value - The list of server metrics for the server. Value *[]ServerUsage `json:"value,omitempty"` } // ServerVersionCapability the server capability type ServerVersionCapability struct { // Name - READ-ONLY; The server version name. Name *string `json:"name,omitempty"` // SupportedEditions - READ-ONLY; The list of supported database editions. SupportedEditions *[]EditionCapability `json:"supportedEditions,omitempty"` // SupportedElasticPoolEditions - READ-ONLY; The list of supported elastic pool editions. SupportedElasticPoolEditions *[]ElasticPoolEditionCapability `json:"supportedElasticPoolEditions,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ServerVulnerabilityAssessment a server vulnerability assessment. type ServerVulnerabilityAssessment struct { autorest.Response `json:"-"` // ServerVulnerabilityAssessmentProperties - Resource properties. *ServerVulnerabilityAssessmentProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServerVulnerabilityAssessment. func (sva ServerVulnerabilityAssessment) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if sva.ServerVulnerabilityAssessmentProperties != nil { objectMap["properties"] = sva.ServerVulnerabilityAssessmentProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServerVulnerabilityAssessment struct. func (sva *ServerVulnerabilityAssessment) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var serverVulnerabilityAssessmentProperties ServerVulnerabilityAssessmentProperties err = json.Unmarshal(*v, &serverVulnerabilityAssessmentProperties) if err != nil { return err } sva.ServerVulnerabilityAssessmentProperties = &serverVulnerabilityAssessmentProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sva.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sva.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sva.Type = &typeVar } } } return nil } // ServerVulnerabilityAssessmentListResult a list of the server's vulnerability assessments. type ServerVulnerabilityAssessmentListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]ServerVulnerabilityAssessment `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // ServerVulnerabilityAssessmentListResultIterator provides access to a complete listing of // ServerVulnerabilityAssessment values. type ServerVulnerabilityAssessmentListResultIterator struct { i int page ServerVulnerabilityAssessmentListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *ServerVulnerabilityAssessmentListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServerVulnerabilityAssessmentListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *ServerVulnerabilityAssessmentListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter ServerVulnerabilityAssessmentListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter ServerVulnerabilityAssessmentListResultIterator) Response() ServerVulnerabilityAssessmentListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter ServerVulnerabilityAssessmentListResultIterator) Value() ServerVulnerabilityAssessment { if !iter.page.NotDone() { return ServerVulnerabilityAssessment{} } return iter.page.Values()[iter.i] } // Creates a new instance of the ServerVulnerabilityAssessmentListResultIterator type. func NewServerVulnerabilityAssessmentListResultIterator(page ServerVulnerabilityAssessmentListResultPage) ServerVulnerabilityAssessmentListResultIterator { return ServerVulnerabilityAssessmentListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (svalr ServerVulnerabilityAssessmentListResult) IsEmpty() bool { return svalr.Value == nil || len(*svalr.Value) == 0 } // serverVulnerabilityAssessmentListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (svalr ServerVulnerabilityAssessmentListResult) serverVulnerabilityAssessmentListResultPreparer(ctx context.Context) (*http.Request, error) { if svalr.NextLink == nil || len(to.String(svalr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(svalr.NextLink))) } // ServerVulnerabilityAssessmentListResultPage contains a page of ServerVulnerabilityAssessment values. type ServerVulnerabilityAssessmentListResultPage struct { fn func(context.Context, ServerVulnerabilityAssessmentListResult) (ServerVulnerabilityAssessmentListResult, error) svalr ServerVulnerabilityAssessmentListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *ServerVulnerabilityAssessmentListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/ServerVulnerabilityAssessmentListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.svalr) if err != nil { return err } page.svalr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *ServerVulnerabilityAssessmentListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page ServerVulnerabilityAssessmentListResultPage) NotDone() bool { return !page.svalr.IsEmpty() } // Response returns the raw server response from the last page request. func (page ServerVulnerabilityAssessmentListResultPage) Response() ServerVulnerabilityAssessmentListResult { return page.svalr } // Values returns the slice of values for the current page or nil if there are no values. func (page ServerVulnerabilityAssessmentListResultPage) Values() []ServerVulnerabilityAssessment { if page.svalr.IsEmpty() { return nil } return *page.svalr.Value } // Creates a new instance of the ServerVulnerabilityAssessmentListResultPage type. func NewServerVulnerabilityAssessmentListResultPage(getNextPage func(context.Context, ServerVulnerabilityAssessmentListResult) (ServerVulnerabilityAssessmentListResult, error)) ServerVulnerabilityAssessmentListResultPage { return ServerVulnerabilityAssessmentListResultPage{fn: getNextPage} } // ServerVulnerabilityAssessmentProperties properties of a server Vulnerability Assessment. type ServerVulnerabilityAssessmentProperties struct { // StorageContainerPath - A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/). StorageContainerPath *string `json:"storageContainerPath,omitempty"` // StorageContainerSasKey - A shared access signature (SAS Key) that has write access to the blob container specified in 'storageContainerPath' parameter. If 'storageAccountAccessKey' isn't specified, StorageContainerSasKey is required. StorageContainerSasKey *string `json:"storageContainerSasKey,omitempty"` // StorageAccountAccessKey - Specifies the identifier key of the storage account for vulnerability assessment scan results. If 'StorageContainerSasKey' isn't specified, storageAccountAccessKey is required. StorageAccountAccessKey *string `json:"storageAccountAccessKey,omitempty"` // RecurringScans - The recurring scans settings RecurringScans *VulnerabilityAssessmentRecurringScansProperties `json:"recurringScans,omitempty"` } // ServiceObjective represents a database service objective. type ServiceObjective struct { autorest.Response `json:"-"` // ServiceObjectiveProperties - Represents the properties of the resource. *ServiceObjectiveProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServiceObjective. func (so ServiceObjective) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if so.ServiceObjectiveProperties != nil { objectMap["properties"] = so.ServiceObjectiveProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServiceObjective struct. func (so *ServiceObjective) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var serviceObjectiveProperties ServiceObjectiveProperties err = json.Unmarshal(*v, &serviceObjectiveProperties) if err != nil { return err } so.ServiceObjectiveProperties = &serviceObjectiveProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } so.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } so.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } so.Type = &typeVar } } } return nil } // ServiceObjectiveCapability the service objectives capability. type ServiceObjectiveCapability struct { // ID - READ-ONLY; The unique ID of the service objective. ID *uuid.UUID `json:"id,omitempty"` // Name - READ-ONLY; The service objective name. Name *string `json:"name,omitempty"` // SupportedMaxSizes - READ-ONLY; The list of supported maximum database sizes. SupportedMaxSizes *[]MaxSizeRangeCapability `json:"supportedMaxSizes,omitempty"` // PerformanceLevel - READ-ONLY; The performance level. PerformanceLevel *PerformanceLevelCapability `json:"performanceLevel,omitempty"` // Sku - READ-ONLY; The sku. Sku *Sku `json:"sku,omitempty"` // SupportedLicenseTypes - READ-ONLY; List of supported license types. SupportedLicenseTypes *[]LicenseTypeCapability `json:"supportedLicenseTypes,omitempty"` // IncludedMaxSize - READ-ONLY; The included (free) max size. IncludedMaxSize *MaxSizeCapability `json:"includedMaxSize,omitempty"` // Status - READ-ONLY; The status of the capability. Possible values include: 'CapabilityStatusVisible', 'CapabilityStatusAvailable', 'CapabilityStatusDefault', 'CapabilityStatusDisabled' Status CapabilityStatus `json:"status,omitempty"` // Reason - The reason for the capability not being available. Reason *string `json:"reason,omitempty"` } // ServiceObjectiveListResult represents the response to a get database service objectives request. type ServiceObjectiveListResult struct { autorest.Response `json:"-"` // Value - The list of database service objectives. Value *[]ServiceObjective `json:"value,omitempty"` } // ServiceObjectiveProperties represents the properties of a database service objective. type ServiceObjectiveProperties struct { // ServiceObjectiveName - READ-ONLY; The name for the service objective. ServiceObjectiveName *string `json:"serviceObjectiveName,omitempty"` // IsDefault - READ-ONLY; Gets whether the service level objective is the default service objective. IsDefault *bool `json:"isDefault,omitempty"` // IsSystem - READ-ONLY; Gets whether the service level objective is a system service objective. IsSystem *bool `json:"isSystem,omitempty"` // Description - READ-ONLY; The description for the service level objective. Description *string `json:"description,omitempty"` // Enabled - READ-ONLY; Gets whether the service level objective is enabled. Enabled *bool `json:"enabled,omitempty"` } // ServiceTierAdvisor represents a Service Tier Advisor. type ServiceTierAdvisor struct { autorest.Response `json:"-"` // ServiceTierAdvisorProperties - READ-ONLY; The properties representing the resource. *ServiceTierAdvisorProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for ServiceTierAdvisor. func (sta ServiceTierAdvisor) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for ServiceTierAdvisor struct. func (sta *ServiceTierAdvisor) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var serviceTierAdvisorProperties ServiceTierAdvisorProperties err = json.Unmarshal(*v, &serviceTierAdvisorProperties) if err != nil { return err } sta.ServiceTierAdvisorProperties = &serviceTierAdvisorProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sta.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sta.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sta.Type = &typeVar } } } return nil } // ServiceTierAdvisorListResult represents the response to a list service tier advisor request. type ServiceTierAdvisorListResult struct { autorest.Response `json:"-"` // Value - The list of service tier advisors for specified database. Value *[]ServiceTierAdvisor `json:"value,omitempty"` } // ServiceTierAdvisorProperties represents the properties of a Service Tier Advisor. type ServiceTierAdvisorProperties struct { // ObservationPeriodStart - READ-ONLY; The observation period start (ISO8601 format). ObservationPeriodStart *date.Time `json:"observationPeriodStart,omitempty"` // ObservationPeriodEnd - READ-ONLY; The observation period start (ISO8601 format). ObservationPeriodEnd *date.Time `json:"observationPeriodEnd,omitempty"` // ActiveTimeRatio - READ-ONLY; The activeTimeRatio for service tier advisor. ActiveTimeRatio *float64 `json:"activeTimeRatio,omitempty"` // MinDtu - READ-ONLY; Gets or sets minDtu for service tier advisor. MinDtu *float64 `json:"minDtu,omitempty"` // AvgDtu - READ-ONLY; Gets or sets avgDtu for service tier advisor. AvgDtu *float64 `json:"avgDtu,omitempty"` // MaxDtu - READ-ONLY; Gets or sets maxDtu for service tier advisor. MaxDtu *float64 `json:"maxDtu,omitempty"` // MaxSizeInGB - READ-ONLY; Gets or sets maxSizeInGB for service tier advisor. MaxSizeInGB *float64 `json:"maxSizeInGB,omitempty"` // ServiceLevelObjectiveUsageMetrics - READ-ONLY; Gets or sets serviceLevelObjectiveUsageMetrics for the service tier advisor. ServiceLevelObjectiveUsageMetrics *[]SloUsageMetric `json:"serviceLevelObjectiveUsageMetrics,omitempty"` // CurrentServiceLevelObjective - READ-ONLY; Gets or sets currentServiceLevelObjective for service tier advisor. CurrentServiceLevelObjective *string `json:"currentServiceLevelObjective,omitempty"` // CurrentServiceLevelObjectiveID - READ-ONLY; Gets or sets currentServiceLevelObjectiveId for service tier advisor. CurrentServiceLevelObjectiveID *uuid.UUID `json:"currentServiceLevelObjectiveId,omitempty"` // UsageBasedRecommendationServiceLevelObjective - READ-ONLY; Gets or sets usageBasedRecommendationServiceLevelObjective for service tier advisor. UsageBasedRecommendationServiceLevelObjective *string `json:"usageBasedRecommendationServiceLevelObjective,omitempty"` // UsageBasedRecommendationServiceLevelObjectiveID - READ-ONLY; Gets or sets usageBasedRecommendationServiceLevelObjectiveId for service tier advisor. UsageBasedRecommendationServiceLevelObjectiveID *uuid.UUID `json:"usageBasedRecommendationServiceLevelObjectiveId,omitempty"` // DatabaseSizeBasedRecommendationServiceLevelObjective - READ-ONLY; Gets or sets databaseSizeBasedRecommendationServiceLevelObjective for service tier advisor. DatabaseSizeBasedRecommendationServiceLevelObjective *string `json:"databaseSizeBasedRecommendationServiceLevelObjective,omitempty"` // DatabaseSizeBasedRecommendationServiceLevelObjectiveID - READ-ONLY; Gets or sets databaseSizeBasedRecommendationServiceLevelObjectiveId for service tier advisor. DatabaseSizeBasedRecommendationServiceLevelObjectiveID *uuid.UUID `json:"databaseSizeBasedRecommendationServiceLevelObjectiveId,omitempty"` // DisasterPlanBasedRecommendationServiceLevelObjective - READ-ONLY; Gets or sets disasterPlanBasedRecommendationServiceLevelObjective for service tier advisor. DisasterPlanBasedRecommendationServiceLevelObjective *string `json:"disasterPlanBasedRecommendationServiceLevelObjective,omitempty"` // DisasterPlanBasedRecommendationServiceLevelObjectiveID - READ-ONLY; Gets or sets disasterPlanBasedRecommendationServiceLevelObjectiveId for service tier advisor. DisasterPlanBasedRecommendationServiceLevelObjectiveID *uuid.UUID `json:"disasterPlanBasedRecommendationServiceLevelObjectiveId,omitempty"` // OverallRecommendationServiceLevelObjective - READ-ONLY; Gets or sets overallRecommendationServiceLevelObjective for service tier advisor. OverallRecommendationServiceLevelObjective *string `json:"overallRecommendationServiceLevelObjective,omitempty"` // OverallRecommendationServiceLevelObjectiveID - READ-ONLY; Gets or sets overallRecommendationServiceLevelObjectiveId for service tier advisor. OverallRecommendationServiceLevelObjectiveID *uuid.UUID `json:"overallRecommendationServiceLevelObjectiveId,omitempty"` // Confidence - READ-ONLY; Gets or sets confidence for service tier advisor. Confidence *float64 `json:"confidence,omitempty"` } // Sku an ARM Resource SKU. type Sku struct { // Name - The name of the SKU, typically, a letter + Number code, e.g. P3. Name *string `json:"name,omitempty"` // Tier - The tier or edition of the particular SKU, e.g. Basic, Premium. Tier *string `json:"tier,omitempty"` // Size - Size of the particular SKU Size *string `json:"size,omitempty"` // Family - If the service has different generations of hardware, for the same SKU, then that can be captured here. Family *string `json:"family,omitempty"` // Capacity - Capacity of the particular SKU. Capacity *int32 `json:"capacity,omitempty"` } // SloUsageMetric a Slo Usage Metric. type SloUsageMetric struct { // ServiceLevelObjective - READ-ONLY; The serviceLevelObjective for SLO usage metric. Possible values include: 'ServiceObjectiveNameSystem', 'ServiceObjectiveNameSystem0', 'ServiceObjectiveNameSystem1', 'ServiceObjectiveNameSystem2', 'ServiceObjectiveNameSystem3', 'ServiceObjectiveNameSystem4', 'ServiceObjectiveNameSystem2L', 'ServiceObjectiveNameSystem3L', 'ServiceObjectiveNameSystem4L', 'ServiceObjectiveNameFree', 'ServiceObjectiveNameBasic', 'ServiceObjectiveNameS0', 'ServiceObjectiveNameS1', 'ServiceObjectiveNameS2', 'ServiceObjectiveNameS3', 'ServiceObjectiveNameS4', 'ServiceObjectiveNameS6', 'ServiceObjectiveNameS7', 'ServiceObjectiveNameS9', 'ServiceObjectiveNameS12', 'ServiceObjectiveNameP1', 'ServiceObjectiveNameP2', 'ServiceObjectiveNameP3', 'ServiceObjectiveNameP4', 'ServiceObjectiveNameP6', 'ServiceObjectiveNameP11', 'ServiceObjectiveNameP15', 'ServiceObjectiveNamePRS1', 'ServiceObjectiveNamePRS2', 'ServiceObjectiveNamePRS4', 'ServiceObjectiveNamePRS6', 'ServiceObjectiveNameDW100', 'ServiceObjectiveNameDW200', 'ServiceObjectiveNameDW300', 'ServiceObjectiveNameDW400', 'ServiceObjectiveNameDW500', 'ServiceObjectiveNameDW600', 'ServiceObjectiveNameDW1000', 'ServiceObjectiveNameDW1200', 'ServiceObjectiveNameDW1000c', 'ServiceObjectiveNameDW1500', 'ServiceObjectiveNameDW1500c', 'ServiceObjectiveNameDW2000', 'ServiceObjectiveNameDW2000c', 'ServiceObjectiveNameDW3000', 'ServiceObjectiveNameDW2500c', 'ServiceObjectiveNameDW3000c', 'ServiceObjectiveNameDW6000', 'ServiceObjectiveNameDW5000c', 'ServiceObjectiveNameDW6000c', 'ServiceObjectiveNameDW7500c', 'ServiceObjectiveNameDW10000c', 'ServiceObjectiveNameDW15000c', 'ServiceObjectiveNameDW30000c', 'ServiceObjectiveNameDS100', 'ServiceObjectiveNameDS200', 'ServiceObjectiveNameDS300', 'ServiceObjectiveNameDS400', 'ServiceObjectiveNameDS500', 'ServiceObjectiveNameDS600', 'ServiceObjectiveNameDS1000', 'ServiceObjectiveNameDS1200', 'ServiceObjectiveNameDS1500', 'ServiceObjectiveNameDS2000', 'ServiceObjectiveNameElasticPool' ServiceLevelObjective ServiceObjectiveName `json:"serviceLevelObjective,omitempty"` // ServiceLevelObjectiveID - READ-ONLY; The serviceLevelObjectiveId for SLO usage metric. ServiceLevelObjectiveID *uuid.UUID `json:"serviceLevelObjectiveId,omitempty"` // InRangeTimeRatio - READ-ONLY; Gets or sets inRangeTimeRatio for SLO usage metric. InRangeTimeRatio *float64 `json:"inRangeTimeRatio,omitempty"` } // SubscriptionUsage usage Metric of a Subscription in a Location. type SubscriptionUsage struct { autorest.Response `json:"-"` // SubscriptionUsageProperties - Resource properties. *SubscriptionUsageProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for SubscriptionUsage. func (su SubscriptionUsage) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if su.SubscriptionUsageProperties != nil { objectMap["properties"] = su.SubscriptionUsageProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for SubscriptionUsage struct. func (su *SubscriptionUsage) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var subscriptionUsageProperties SubscriptionUsageProperties err = json.Unmarshal(*v, &subscriptionUsageProperties) if err != nil { return err } su.SubscriptionUsageProperties = &subscriptionUsageProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } su.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } su.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } su.Type = &typeVar } } } return nil } // SubscriptionUsageListResult a list of subscription usage metrics in a location. type SubscriptionUsageListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]SubscriptionUsage `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // SubscriptionUsageListResultIterator provides access to a complete listing of SubscriptionUsage values. type SubscriptionUsageListResultIterator struct { i int page SubscriptionUsageListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *SubscriptionUsageListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionUsageListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *SubscriptionUsageListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter SubscriptionUsageListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter SubscriptionUsageListResultIterator) Response() SubscriptionUsageListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter SubscriptionUsageListResultIterator) Value() SubscriptionUsage { if !iter.page.NotDone() { return SubscriptionUsage{} } return iter.page.Values()[iter.i] } // Creates a new instance of the SubscriptionUsageListResultIterator type. func NewSubscriptionUsageListResultIterator(page SubscriptionUsageListResultPage) SubscriptionUsageListResultIterator { return SubscriptionUsageListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (sulr SubscriptionUsageListResult) IsEmpty() bool { return sulr.Value == nil || len(*sulr.Value) == 0 } // subscriptionUsageListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (sulr SubscriptionUsageListResult) subscriptionUsageListResultPreparer(ctx context.Context) (*http.Request, error) { if sulr.NextLink == nil || len(to.String(sulr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(sulr.NextLink))) } // SubscriptionUsageListResultPage contains a page of SubscriptionUsage values. type SubscriptionUsageListResultPage struct { fn func(context.Context, SubscriptionUsageListResult) (SubscriptionUsageListResult, error) sulr SubscriptionUsageListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *SubscriptionUsageListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SubscriptionUsageListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.sulr) if err != nil { return err } page.sulr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *SubscriptionUsageListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page SubscriptionUsageListResultPage) NotDone() bool { return !page.sulr.IsEmpty() } // Response returns the raw server response from the last page request. func (page SubscriptionUsageListResultPage) Response() SubscriptionUsageListResult { return page.sulr } // Values returns the slice of values for the current page or nil if there are no values. func (page SubscriptionUsageListResultPage) Values() []SubscriptionUsage { if page.sulr.IsEmpty() { return nil } return *page.sulr.Value } // Creates a new instance of the SubscriptionUsageListResultPage type. func NewSubscriptionUsageListResultPage(getNextPage func(context.Context, SubscriptionUsageListResult) (SubscriptionUsageListResult, error)) SubscriptionUsageListResultPage { return SubscriptionUsageListResultPage{fn: getNextPage} } // SubscriptionUsageProperties properties of a subscription usage. type SubscriptionUsageProperties struct { // DisplayName - READ-ONLY; User-readable name of the metric. DisplayName *string `json:"displayName,omitempty"` // CurrentValue - READ-ONLY; Current value of the metric. CurrentValue *float64 `json:"currentValue,omitempty"` // Limit - READ-ONLY; Boundary value of the metric. Limit *float64 `json:"limit,omitempty"` // Unit - READ-ONLY; Unit of the metric. Unit *string `json:"unit,omitempty"` } // SyncAgent an Azure SQL Database sync agent. type SyncAgent struct { autorest.Response `json:"-"` // SyncAgentProperties - Resource properties. *SyncAgentProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for SyncAgent. func (sa SyncAgent) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if sa.SyncAgentProperties != nil { objectMap["properties"] = sa.SyncAgentProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for SyncAgent struct. func (sa *SyncAgent) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var syncAgentProperties SyncAgentProperties err = json.Unmarshal(*v, &syncAgentProperties) if err != nil { return err } sa.SyncAgentProperties = &syncAgentProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sa.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sa.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sa.Type = &typeVar } } } return nil } // SyncAgentKeyProperties properties of an Azure SQL Database sync agent key. type SyncAgentKeyProperties struct { autorest.Response `json:"-"` // SyncAgentKey - READ-ONLY; Key of sync agent. SyncAgentKey *string `json:"syncAgentKey,omitempty"` } // SyncAgentLinkedDatabase an Azure SQL Database sync agent linked database. type SyncAgentLinkedDatabase struct { // SyncAgentLinkedDatabaseProperties - Resource properties. *SyncAgentLinkedDatabaseProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for SyncAgentLinkedDatabase. func (sald SyncAgentLinkedDatabase) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if sald.SyncAgentLinkedDatabaseProperties != nil { objectMap["properties"] = sald.SyncAgentLinkedDatabaseProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for SyncAgentLinkedDatabase struct. func (sald *SyncAgentLinkedDatabase) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var syncAgentLinkedDatabaseProperties SyncAgentLinkedDatabaseProperties err = json.Unmarshal(*v, &syncAgentLinkedDatabaseProperties) if err != nil { return err } sald.SyncAgentLinkedDatabaseProperties = &syncAgentLinkedDatabaseProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sald.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sald.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sald.Type = &typeVar } } } return nil } // SyncAgentLinkedDatabaseListResult a list of sync agent linked databases. type SyncAgentLinkedDatabaseListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]SyncAgentLinkedDatabase `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // SyncAgentLinkedDatabaseListResultIterator provides access to a complete listing of // SyncAgentLinkedDatabase values. type SyncAgentLinkedDatabaseListResultIterator struct { i int page SyncAgentLinkedDatabaseListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *SyncAgentLinkedDatabaseListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncAgentLinkedDatabaseListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *SyncAgentLinkedDatabaseListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter SyncAgentLinkedDatabaseListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter SyncAgentLinkedDatabaseListResultIterator) Response() SyncAgentLinkedDatabaseListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter SyncAgentLinkedDatabaseListResultIterator) Value() SyncAgentLinkedDatabase { if !iter.page.NotDone() { return SyncAgentLinkedDatabase{} } return iter.page.Values()[iter.i] } // Creates a new instance of the SyncAgentLinkedDatabaseListResultIterator type. func NewSyncAgentLinkedDatabaseListResultIterator(page SyncAgentLinkedDatabaseListResultPage) SyncAgentLinkedDatabaseListResultIterator { return SyncAgentLinkedDatabaseListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (saldlr SyncAgentLinkedDatabaseListResult) IsEmpty() bool { return saldlr.Value == nil || len(*saldlr.Value) == 0 } // syncAgentLinkedDatabaseListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (saldlr SyncAgentLinkedDatabaseListResult) syncAgentLinkedDatabaseListResultPreparer(ctx context.Context) (*http.Request, error) { if saldlr.NextLink == nil || len(to.String(saldlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(saldlr.NextLink))) } // SyncAgentLinkedDatabaseListResultPage contains a page of SyncAgentLinkedDatabase values. type SyncAgentLinkedDatabaseListResultPage struct { fn func(context.Context, SyncAgentLinkedDatabaseListResult) (SyncAgentLinkedDatabaseListResult, error) saldlr SyncAgentLinkedDatabaseListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *SyncAgentLinkedDatabaseListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncAgentLinkedDatabaseListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.saldlr) if err != nil { return err } page.saldlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *SyncAgentLinkedDatabaseListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page SyncAgentLinkedDatabaseListResultPage) NotDone() bool { return !page.saldlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page SyncAgentLinkedDatabaseListResultPage) Response() SyncAgentLinkedDatabaseListResult { return page.saldlr } // Values returns the slice of values for the current page or nil if there are no values. func (page SyncAgentLinkedDatabaseListResultPage) Values() []SyncAgentLinkedDatabase { if page.saldlr.IsEmpty() { return nil } return *page.saldlr.Value } // Creates a new instance of the SyncAgentLinkedDatabaseListResultPage type. func NewSyncAgentLinkedDatabaseListResultPage(getNextPage func(context.Context, SyncAgentLinkedDatabaseListResult) (SyncAgentLinkedDatabaseListResult, error)) SyncAgentLinkedDatabaseListResultPage { return SyncAgentLinkedDatabaseListResultPage{fn: getNextPage} } // SyncAgentLinkedDatabaseProperties properties of an Azure SQL Database sync agent linked database. type SyncAgentLinkedDatabaseProperties struct { // DatabaseType - READ-ONLY; Type of the sync agent linked database. Possible values include: 'AzureSQLDatabase', 'SQLServerDatabase' DatabaseType SyncMemberDbType `json:"databaseType,omitempty"` // DatabaseID - READ-ONLY; Id of the sync agent linked database. DatabaseID *string `json:"databaseId,omitempty"` // Description - READ-ONLY; Description of the sync agent linked database. Description *string `json:"description,omitempty"` // ServerName - READ-ONLY; Server name of the sync agent linked database. ServerName *string `json:"serverName,omitempty"` // DatabaseName - READ-ONLY; Database name of the sync agent linked database. DatabaseName *string `json:"databaseName,omitempty"` // UserName - READ-ONLY; User name of the sync agent linked database. UserName *string `json:"userName,omitempty"` } // SyncAgentListResult a list of sync agents. type SyncAgentListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]SyncAgent `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // SyncAgentListResultIterator provides access to a complete listing of SyncAgent values. type SyncAgentListResultIterator struct { i int page SyncAgentListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *SyncAgentListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncAgentListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *SyncAgentListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter SyncAgentListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter SyncAgentListResultIterator) Response() SyncAgentListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter SyncAgentListResultIterator) Value() SyncAgent { if !iter.page.NotDone() { return SyncAgent{} } return iter.page.Values()[iter.i] } // Creates a new instance of the SyncAgentListResultIterator type. func NewSyncAgentListResultIterator(page SyncAgentListResultPage) SyncAgentListResultIterator { return SyncAgentListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (salr SyncAgentListResult) IsEmpty() bool { return salr.Value == nil || len(*salr.Value) == 0 } // syncAgentListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (salr SyncAgentListResult) syncAgentListResultPreparer(ctx context.Context) (*http.Request, error) { if salr.NextLink == nil || len(to.String(salr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(salr.NextLink))) } // SyncAgentListResultPage contains a page of SyncAgent values. type SyncAgentListResultPage struct { fn func(context.Context, SyncAgentListResult) (SyncAgentListResult, error) salr SyncAgentListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *SyncAgentListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncAgentListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.salr) if err != nil { return err } page.salr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *SyncAgentListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page SyncAgentListResultPage) NotDone() bool { return !page.salr.IsEmpty() } // Response returns the raw server response from the last page request. func (page SyncAgentListResultPage) Response() SyncAgentListResult { return page.salr } // Values returns the slice of values for the current page or nil if there are no values. func (page SyncAgentListResultPage) Values() []SyncAgent { if page.salr.IsEmpty() { return nil } return *page.salr.Value } // Creates a new instance of the SyncAgentListResultPage type. func NewSyncAgentListResultPage(getNextPage func(context.Context, SyncAgentListResult) (SyncAgentListResult, error)) SyncAgentListResultPage { return SyncAgentListResultPage{fn: getNextPage} } // SyncAgentProperties properties of an Azure SQL Database sync agent. type SyncAgentProperties struct { // Name - READ-ONLY; Name of the sync agent. Name *string `json:"name,omitempty"` // SyncDatabaseID - ARM resource id of the sync database in the sync agent. SyncDatabaseID *string `json:"syncDatabaseId,omitempty"` // LastAliveTime - READ-ONLY; Last alive time of the sync agent. LastAliveTime *date.Time `json:"lastAliveTime,omitempty"` // State - READ-ONLY; State of the sync agent. Possible values include: 'SyncAgentStateOnline', 'SyncAgentStateOffline', 'SyncAgentStateNeverConnected' State SyncAgentState `json:"state,omitempty"` // IsUpToDate - READ-ONLY; If the sync agent version is up to date. IsUpToDate *bool `json:"isUpToDate,omitempty"` // ExpiryTime - READ-ONLY; Expiration time of the sync agent version. ExpiryTime *date.Time `json:"expiryTime,omitempty"` // Version - READ-ONLY; Version of the sync agent. Version *string `json:"version,omitempty"` } // SyncAgentsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type SyncAgentsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *SyncAgentsCreateOrUpdateFuture) Result(client SyncAgentsClient) (sa SyncAgent, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncAgentsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.SyncAgentsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if sa.Response.Response, err = future.GetResult(sender); err == nil && sa.Response.Response.StatusCode != http.StatusNoContent { sa, err = client.CreateOrUpdateResponder(sa.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncAgentsCreateOrUpdateFuture", "Result", sa.Response.Response, "Failure responding to request") } } return } // SyncAgentsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type SyncAgentsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *SyncAgentsDeleteFuture) Result(client SyncAgentsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncAgentsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.SyncAgentsDeleteFuture") return } ar.Response = future.Response() return } // SyncDatabaseIDListResult a list of sync database ID properties. type SyncDatabaseIDListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]SyncDatabaseIDProperties `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // SyncDatabaseIDListResultIterator provides access to a complete listing of SyncDatabaseIDProperties // values. type SyncDatabaseIDListResultIterator struct { i int page SyncDatabaseIDListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *SyncDatabaseIDListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncDatabaseIDListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *SyncDatabaseIDListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter SyncDatabaseIDListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter SyncDatabaseIDListResultIterator) Response() SyncDatabaseIDListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter SyncDatabaseIDListResultIterator) Value() SyncDatabaseIDProperties { if !iter.page.NotDone() { return SyncDatabaseIDProperties{} } return iter.page.Values()[iter.i] } // Creates a new instance of the SyncDatabaseIDListResultIterator type. func NewSyncDatabaseIDListResultIterator(page SyncDatabaseIDListResultPage) SyncDatabaseIDListResultIterator { return SyncDatabaseIDListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (sdilr SyncDatabaseIDListResult) IsEmpty() bool { return sdilr.Value == nil || len(*sdilr.Value) == 0 } // syncDatabaseIDListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (sdilr SyncDatabaseIDListResult) syncDatabaseIDListResultPreparer(ctx context.Context) (*http.Request, error) { if sdilr.NextLink == nil || len(to.String(sdilr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(sdilr.NextLink))) } // SyncDatabaseIDListResultPage contains a page of SyncDatabaseIDProperties values. type SyncDatabaseIDListResultPage struct { fn func(context.Context, SyncDatabaseIDListResult) (SyncDatabaseIDListResult, error) sdilr SyncDatabaseIDListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *SyncDatabaseIDListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncDatabaseIDListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.sdilr) if err != nil { return err } page.sdilr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *SyncDatabaseIDListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page SyncDatabaseIDListResultPage) NotDone() bool { return !page.sdilr.IsEmpty() } // Response returns the raw server response from the last page request. func (page SyncDatabaseIDListResultPage) Response() SyncDatabaseIDListResult { return page.sdilr } // Values returns the slice of values for the current page or nil if there are no values. func (page SyncDatabaseIDListResultPage) Values() []SyncDatabaseIDProperties { if page.sdilr.IsEmpty() { return nil } return *page.sdilr.Value } // Creates a new instance of the SyncDatabaseIDListResultPage type. func NewSyncDatabaseIDListResultPage(getNextPage func(context.Context, SyncDatabaseIDListResult) (SyncDatabaseIDListResult, error)) SyncDatabaseIDListResultPage { return SyncDatabaseIDListResultPage{fn: getNextPage} } // SyncDatabaseIDProperties properties of the sync database id. type SyncDatabaseIDProperties struct { // ID - READ-ONLY; ARM resource id of sync database. ID *string `json:"id,omitempty"` } // SyncFullSchemaProperties properties of the database full schema. type SyncFullSchemaProperties struct { // Tables - READ-ONLY; List of tables in the database full schema. Tables *[]SyncFullSchemaTable `json:"tables,omitempty"` // LastUpdateTime - READ-ONLY; Last update time of the database schema. LastUpdateTime *date.Time `json:"lastUpdateTime,omitempty"` } // SyncFullSchemaPropertiesListResult a list of sync schema properties. type SyncFullSchemaPropertiesListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]SyncFullSchemaProperties `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // SyncFullSchemaPropertiesListResultIterator provides access to a complete listing of // SyncFullSchemaProperties values. type SyncFullSchemaPropertiesListResultIterator struct { i int page SyncFullSchemaPropertiesListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *SyncFullSchemaPropertiesListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncFullSchemaPropertiesListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *SyncFullSchemaPropertiesListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter SyncFullSchemaPropertiesListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter SyncFullSchemaPropertiesListResultIterator) Response() SyncFullSchemaPropertiesListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter SyncFullSchemaPropertiesListResultIterator) Value() SyncFullSchemaProperties { if !iter.page.NotDone() { return SyncFullSchemaProperties{} } return iter.page.Values()[iter.i] } // Creates a new instance of the SyncFullSchemaPropertiesListResultIterator type. func NewSyncFullSchemaPropertiesListResultIterator(page SyncFullSchemaPropertiesListResultPage) SyncFullSchemaPropertiesListResultIterator { return SyncFullSchemaPropertiesListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (sfsplr SyncFullSchemaPropertiesListResult) IsEmpty() bool { return sfsplr.Value == nil || len(*sfsplr.Value) == 0 } // syncFullSchemaPropertiesListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (sfsplr SyncFullSchemaPropertiesListResult) syncFullSchemaPropertiesListResultPreparer(ctx context.Context) (*http.Request, error) { if sfsplr.NextLink == nil || len(to.String(sfsplr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(sfsplr.NextLink))) } // SyncFullSchemaPropertiesListResultPage contains a page of SyncFullSchemaProperties values. type SyncFullSchemaPropertiesListResultPage struct { fn func(context.Context, SyncFullSchemaPropertiesListResult) (SyncFullSchemaPropertiesListResult, error) sfsplr SyncFullSchemaPropertiesListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *SyncFullSchemaPropertiesListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncFullSchemaPropertiesListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.sfsplr) if err != nil { return err } page.sfsplr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *SyncFullSchemaPropertiesListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page SyncFullSchemaPropertiesListResultPage) NotDone() bool { return !page.sfsplr.IsEmpty() } // Response returns the raw server response from the last page request. func (page SyncFullSchemaPropertiesListResultPage) Response() SyncFullSchemaPropertiesListResult { return page.sfsplr } // Values returns the slice of values for the current page or nil if there are no values. func (page SyncFullSchemaPropertiesListResultPage) Values() []SyncFullSchemaProperties { if page.sfsplr.IsEmpty() { return nil } return *page.sfsplr.Value } // Creates a new instance of the SyncFullSchemaPropertiesListResultPage type. func NewSyncFullSchemaPropertiesListResultPage(getNextPage func(context.Context, SyncFullSchemaPropertiesListResult) (SyncFullSchemaPropertiesListResult, error)) SyncFullSchemaPropertiesListResultPage { return SyncFullSchemaPropertiesListResultPage{fn: getNextPage} } // SyncFullSchemaTable properties of the table in the database full schema. type SyncFullSchemaTable struct { // Columns - READ-ONLY; List of columns in the table of database full schema. Columns *[]SyncFullSchemaTableColumn `json:"columns,omitempty"` // ErrorID - READ-ONLY; Error id of the table. ErrorID *string `json:"errorId,omitempty"` // HasError - READ-ONLY; If there is error in the table. HasError *bool `json:"hasError,omitempty"` // Name - READ-ONLY; Name of the table. Name *string `json:"name,omitempty"` // QuotedName - READ-ONLY; Quoted name of the table. QuotedName *string `json:"quotedName,omitempty"` } // SyncFullSchemaTableColumn properties of the column in the table of database full schema. type SyncFullSchemaTableColumn struct { // DataSize - READ-ONLY; Data size of the column. DataSize *string `json:"dataSize,omitempty"` // DataType - READ-ONLY; Data type of the column. DataType *string `json:"dataType,omitempty"` // ErrorID - READ-ONLY; Error id of the column. ErrorID *string `json:"errorId,omitempty"` // HasError - READ-ONLY; If there is error in the table. HasError *bool `json:"hasError,omitempty"` // IsPrimaryKey - READ-ONLY; If it is the primary key of the table. IsPrimaryKey *bool `json:"isPrimaryKey,omitempty"` // Name - READ-ONLY; Name of the column. Name *string `json:"name,omitempty"` // QuotedName - READ-ONLY; Quoted name of the column. QuotedName *string `json:"quotedName,omitempty"` } // SyncGroup an Azure SQL Database sync group. type SyncGroup struct { autorest.Response `json:"-"` // SyncGroupProperties - Resource properties. *SyncGroupProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for SyncGroup. func (sg SyncGroup) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if sg.SyncGroupProperties != nil { objectMap["properties"] = sg.SyncGroupProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for SyncGroup struct. func (sg *SyncGroup) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var syncGroupProperties SyncGroupProperties err = json.Unmarshal(*v, &syncGroupProperties) if err != nil { return err } sg.SyncGroupProperties = &syncGroupProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sg.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sg.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sg.Type = &typeVar } } } return nil } // SyncGroupListResult a list of sync groups. type SyncGroupListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]SyncGroup `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // SyncGroupListResultIterator provides access to a complete listing of SyncGroup values. type SyncGroupListResultIterator struct { i int page SyncGroupListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *SyncGroupListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncGroupListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *SyncGroupListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter SyncGroupListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter SyncGroupListResultIterator) Response() SyncGroupListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter SyncGroupListResultIterator) Value() SyncGroup { if !iter.page.NotDone() { return SyncGroup{} } return iter.page.Values()[iter.i] } // Creates a new instance of the SyncGroupListResultIterator type. func NewSyncGroupListResultIterator(page SyncGroupListResultPage) SyncGroupListResultIterator { return SyncGroupListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (sglr SyncGroupListResult) IsEmpty() bool { return sglr.Value == nil || len(*sglr.Value) == 0 } // syncGroupListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (sglr SyncGroupListResult) syncGroupListResultPreparer(ctx context.Context) (*http.Request, error) { if sglr.NextLink == nil || len(to.String(sglr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(sglr.NextLink))) } // SyncGroupListResultPage contains a page of SyncGroup values. type SyncGroupListResultPage struct { fn func(context.Context, SyncGroupListResult) (SyncGroupListResult, error) sglr SyncGroupListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *SyncGroupListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncGroupListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.sglr) if err != nil { return err } page.sglr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *SyncGroupListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page SyncGroupListResultPage) NotDone() bool { return !page.sglr.IsEmpty() } // Response returns the raw server response from the last page request. func (page SyncGroupListResultPage) Response() SyncGroupListResult { return page.sglr } // Values returns the slice of values for the current page or nil if there are no values. func (page SyncGroupListResultPage) Values() []SyncGroup { if page.sglr.IsEmpty() { return nil } return *page.sglr.Value } // Creates a new instance of the SyncGroupListResultPage type. func NewSyncGroupListResultPage(getNextPage func(context.Context, SyncGroupListResult) (SyncGroupListResult, error)) SyncGroupListResultPage { return SyncGroupListResultPage{fn: getNextPage} } // SyncGroupLogListResult a list of sync group log properties. type SyncGroupLogListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]SyncGroupLogProperties `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // SyncGroupLogListResultIterator provides access to a complete listing of SyncGroupLogProperties values. type SyncGroupLogListResultIterator struct { i int page SyncGroupLogListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *SyncGroupLogListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncGroupLogListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *SyncGroupLogListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter SyncGroupLogListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter SyncGroupLogListResultIterator) Response() SyncGroupLogListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter SyncGroupLogListResultIterator) Value() SyncGroupLogProperties { if !iter.page.NotDone() { return SyncGroupLogProperties{} } return iter.page.Values()[iter.i] } // Creates a new instance of the SyncGroupLogListResultIterator type. func NewSyncGroupLogListResultIterator(page SyncGroupLogListResultPage) SyncGroupLogListResultIterator { return SyncGroupLogListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (sgllr SyncGroupLogListResult) IsEmpty() bool { return sgllr.Value == nil || len(*sgllr.Value) == 0 } // syncGroupLogListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (sgllr SyncGroupLogListResult) syncGroupLogListResultPreparer(ctx context.Context) (*http.Request, error) { if sgllr.NextLink == nil || len(to.String(sgllr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(sgllr.NextLink))) } // SyncGroupLogListResultPage contains a page of SyncGroupLogProperties values. type SyncGroupLogListResultPage struct { fn func(context.Context, SyncGroupLogListResult) (SyncGroupLogListResult, error) sgllr SyncGroupLogListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *SyncGroupLogListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncGroupLogListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.sgllr) if err != nil { return err } page.sgllr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *SyncGroupLogListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page SyncGroupLogListResultPage) NotDone() bool { return !page.sgllr.IsEmpty() } // Response returns the raw server response from the last page request. func (page SyncGroupLogListResultPage) Response() SyncGroupLogListResult { return page.sgllr } // Values returns the slice of values for the current page or nil if there are no values. func (page SyncGroupLogListResultPage) Values() []SyncGroupLogProperties { if page.sgllr.IsEmpty() { return nil } return *page.sgllr.Value } // Creates a new instance of the SyncGroupLogListResultPage type. func NewSyncGroupLogListResultPage(getNextPage func(context.Context, SyncGroupLogListResult) (SyncGroupLogListResult, error)) SyncGroupLogListResultPage { return SyncGroupLogListResultPage{fn: getNextPage} } // SyncGroupLogProperties properties of an Azure SQL Database sync group log. type SyncGroupLogProperties struct { // Timestamp - READ-ONLY; Timestamp of the sync group log. Timestamp *date.Time `json:"timestamp,omitempty"` // Type - READ-ONLY; Type of the sync group log. Possible values include: 'SyncGroupLogTypeAll', 'SyncGroupLogTypeError', 'SyncGroupLogTypeWarning', 'SyncGroupLogTypeSuccess' Type SyncGroupLogType `json:"type,omitempty"` // Source - READ-ONLY; Source of the sync group log. Source *string `json:"source,omitempty"` // Details - READ-ONLY; Details of the sync group log. Details *string `json:"details,omitempty"` // TracingID - READ-ONLY; TracingId of the sync group log. TracingID *uuid.UUID `json:"tracingId,omitempty"` // OperationStatus - READ-ONLY; OperationStatus of the sync group log. OperationStatus *string `json:"operationStatus,omitempty"` } // SyncGroupProperties properties of a sync group. type SyncGroupProperties struct { // Interval - Sync interval of the sync group. Interval *int32 `json:"interval,omitempty"` // LastSyncTime - READ-ONLY; Last sync time of the sync group. LastSyncTime *date.Time `json:"lastSyncTime,omitempty"` // ConflictResolutionPolicy - Conflict resolution policy of the sync group. Possible values include: 'HubWin', 'MemberWin' ConflictResolutionPolicy SyncConflictResolutionPolicy `json:"conflictResolutionPolicy,omitempty"` // SyncDatabaseID - ARM resource id of the sync database in the sync group. SyncDatabaseID *string `json:"syncDatabaseId,omitempty"` // HubDatabaseUserName - User name for the sync group hub database credential. HubDatabaseUserName *string `json:"hubDatabaseUserName,omitempty"` // HubDatabasePassword - Password for the sync group hub database credential. HubDatabasePassword *string `json:"hubDatabasePassword,omitempty"` // SyncState - READ-ONLY; Sync state of the sync group. Possible values include: 'NotReady', 'Error', 'Warning', 'Progressing', 'Good' SyncState SyncGroupState `json:"syncState,omitempty"` // Schema - Sync schema of the sync group. Schema *SyncGroupSchema `json:"schema,omitempty"` } // SyncGroupSchema properties of sync group schema. type SyncGroupSchema struct { // Tables - List of tables in sync group schema. Tables *[]SyncGroupSchemaTable `json:"tables,omitempty"` // MasterSyncMemberName - Name of master sync member where the schema is from. MasterSyncMemberName *string `json:"masterSyncMemberName,omitempty"` } // SyncGroupSchemaTable properties of table in sync group schema. type SyncGroupSchemaTable struct { // Columns - List of columns in sync group schema. Columns *[]SyncGroupSchemaTableColumn `json:"columns,omitempty"` // QuotedName - Quoted name of sync group schema table. QuotedName *string `json:"quotedName,omitempty"` } // SyncGroupSchemaTableColumn properties of column in sync group table. type SyncGroupSchemaTableColumn struct { // QuotedName - Quoted name of sync group table column. QuotedName *string `json:"quotedName,omitempty"` // DataSize - Data size of the column. DataSize *string `json:"dataSize,omitempty"` // DataType - Data type of the column. DataType *string `json:"dataType,omitempty"` } // SyncGroupsCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type SyncGroupsCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *SyncGroupsCreateOrUpdateFuture) Result(client SyncGroupsClient) (sg SyncGroup, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncGroupsCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.SyncGroupsCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if sg.Response.Response, err = future.GetResult(sender); err == nil && sg.Response.Response.StatusCode != http.StatusNoContent { sg, err = client.CreateOrUpdateResponder(sg.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncGroupsCreateOrUpdateFuture", "Result", sg.Response.Response, "Failure responding to request") } } return } // SyncGroupsDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type SyncGroupsDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *SyncGroupsDeleteFuture) Result(client SyncGroupsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncGroupsDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.SyncGroupsDeleteFuture") return } ar.Response = future.Response() return } // SyncGroupsRefreshHubSchemaFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type SyncGroupsRefreshHubSchemaFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *SyncGroupsRefreshHubSchemaFuture) Result(client SyncGroupsClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncGroupsRefreshHubSchemaFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.SyncGroupsRefreshHubSchemaFuture") return } ar.Response = future.Response() return } // SyncGroupsUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type SyncGroupsUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *SyncGroupsUpdateFuture) Result(client SyncGroupsClient) (sg SyncGroup, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncGroupsUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.SyncGroupsUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if sg.Response.Response, err = future.GetResult(sender); err == nil && sg.Response.Response.StatusCode != http.StatusNoContent { sg, err = client.UpdateResponder(sg.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncGroupsUpdateFuture", "Result", sg.Response.Response, "Failure responding to request") } } return } // SyncMember an Azure SQL Database sync member. type SyncMember struct { autorest.Response `json:"-"` // SyncMemberProperties - Resource properties. *SyncMemberProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for SyncMember. func (sm SyncMember) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if sm.SyncMemberProperties != nil { objectMap["properties"] = sm.SyncMemberProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for SyncMember struct. func (sm *SyncMember) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var syncMemberProperties SyncMemberProperties err = json.Unmarshal(*v, &syncMemberProperties) if err != nil { return err } sm.SyncMemberProperties = &syncMemberProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } sm.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } sm.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } sm.Type = &typeVar } } } return nil } // SyncMemberListResult a list of Azure SQL Database sync members. type SyncMemberListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]SyncMember `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // SyncMemberListResultIterator provides access to a complete listing of SyncMember values. type SyncMemberListResultIterator struct { i int page SyncMemberListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *SyncMemberListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncMemberListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *SyncMemberListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter SyncMemberListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter SyncMemberListResultIterator) Response() SyncMemberListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter SyncMemberListResultIterator) Value() SyncMember { if !iter.page.NotDone() { return SyncMember{} } return iter.page.Values()[iter.i] } // Creates a new instance of the SyncMemberListResultIterator type. func NewSyncMemberListResultIterator(page SyncMemberListResultPage) SyncMemberListResultIterator { return SyncMemberListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (smlr SyncMemberListResult) IsEmpty() bool { return smlr.Value == nil || len(*smlr.Value) == 0 } // syncMemberListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (smlr SyncMemberListResult) syncMemberListResultPreparer(ctx context.Context) (*http.Request, error) { if smlr.NextLink == nil || len(to.String(smlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(smlr.NextLink))) } // SyncMemberListResultPage contains a page of SyncMember values. type SyncMemberListResultPage struct { fn func(context.Context, SyncMemberListResult) (SyncMemberListResult, error) smlr SyncMemberListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *SyncMemberListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/SyncMemberListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.smlr) if err != nil { return err } page.smlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *SyncMemberListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page SyncMemberListResultPage) NotDone() bool { return !page.smlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page SyncMemberListResultPage) Response() SyncMemberListResult { return page.smlr } // Values returns the slice of values for the current page or nil if there are no values. func (page SyncMemberListResultPage) Values() []SyncMember { if page.smlr.IsEmpty() { return nil } return *page.smlr.Value } // Creates a new instance of the SyncMemberListResultPage type. func NewSyncMemberListResultPage(getNextPage func(context.Context, SyncMemberListResult) (SyncMemberListResult, error)) SyncMemberListResultPage { return SyncMemberListResultPage{fn: getNextPage} } // SyncMemberProperties properties of a sync member. type SyncMemberProperties struct { // DatabaseType - Database type of the sync member. Possible values include: 'AzureSQLDatabase', 'SQLServerDatabase' DatabaseType SyncMemberDbType `json:"databaseType,omitempty"` // SyncAgentID - ARM resource id of the sync agent in the sync member. SyncAgentID *string `json:"syncAgentId,omitempty"` // SQLServerDatabaseID - SQL Server database id of the sync member. SQLServerDatabaseID *uuid.UUID `json:"sqlServerDatabaseId,omitempty"` // ServerName - Server name of the member database in the sync member ServerName *string `json:"serverName,omitempty"` // DatabaseName - Database name of the member database in the sync member. DatabaseName *string `json:"databaseName,omitempty"` // UserName - User name of the member database in the sync member. UserName *string `json:"userName,omitempty"` // Password - Password of the member database in the sync member. Password *string `json:"password,omitempty"` // SyncDirection - Sync direction of the sync member. Possible values include: 'Bidirectional', 'OneWayMemberToHub', 'OneWayHubToMember' SyncDirection SyncDirection `json:"syncDirection,omitempty"` // SyncState - READ-ONLY; Sync state of the sync member. Possible values include: 'SyncInProgress', 'SyncSucceeded', 'SyncFailed', 'DisabledTombstoneCleanup', 'DisabledBackupRestore', 'SyncSucceededWithWarnings', 'SyncCancelling', 'SyncCancelled', 'UnProvisioned', 'Provisioning', 'Provisioned', 'ProvisionFailed', 'DeProvisioning', 'DeProvisioned', 'DeProvisionFailed', 'Reprovisioning', 'ReprovisionFailed', 'UnReprovisioned' SyncState SyncMemberState `json:"syncState,omitempty"` } // SyncMembersCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type SyncMembersCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *SyncMembersCreateOrUpdateFuture) Result(client SyncMembersClient) (sm SyncMember, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncMembersCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.SyncMembersCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if sm.Response.Response, err = future.GetResult(sender); err == nil && sm.Response.Response.StatusCode != http.StatusNoContent { sm, err = client.CreateOrUpdateResponder(sm.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncMembersCreateOrUpdateFuture", "Result", sm.Response.Response, "Failure responding to request") } } return } // SyncMembersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type SyncMembersDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *SyncMembersDeleteFuture) Result(client SyncMembersClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncMembersDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.SyncMembersDeleteFuture") return } ar.Response = future.Response() return } // SyncMembersRefreshMemberSchemaFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type SyncMembersRefreshMemberSchemaFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *SyncMembersRefreshMemberSchemaFuture) Result(client SyncMembersClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncMembersRefreshMemberSchemaFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.SyncMembersRefreshMemberSchemaFuture") return } ar.Response = future.Response() return } // SyncMembersUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type SyncMembersUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *SyncMembersUpdateFuture) Result(client SyncMembersClient) (sm SyncMember, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncMembersUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.SyncMembersUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if sm.Response.Response, err = future.GetResult(sender); err == nil && sm.Response.Response.StatusCode != http.StatusNoContent { sm, err = client.UpdateResponder(sm.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.SyncMembersUpdateFuture", "Result", sm.Response.Response, "Failure responding to request") } } return } // TdeCertificate a TDE certificate that can be uploaded into a server. type TdeCertificate struct { // TdeCertificateProperties - Resource properties. *TdeCertificateProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for TdeCertificate. func (tc TdeCertificate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if tc.TdeCertificateProperties != nil { objectMap["properties"] = tc.TdeCertificateProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for TdeCertificate struct. func (tc *TdeCertificate) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var tdeCertificateProperties TdeCertificateProperties err = json.Unmarshal(*v, &tdeCertificateProperties) if err != nil { return err } tc.TdeCertificateProperties = &tdeCertificateProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } tc.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } tc.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } tc.Type = &typeVar } } } return nil } // TdeCertificateProperties properties of a TDE certificate. type TdeCertificateProperties struct { // PrivateBlob - The base64 encoded certificate private blob. PrivateBlob *string `json:"privateBlob,omitempty"` // CertPassword - The certificate password. CertPassword *string `json:"certPassword,omitempty"` } // TdeCertificatesCreateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type TdeCertificatesCreateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *TdeCertificatesCreateFuture) Result(client TdeCertificatesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.TdeCertificatesCreateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.TdeCertificatesCreateFuture") return } ar.Response = future.Response() return } // TrackedResource ARM tracked top level resource. type TrackedResource struct { // Location - Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for TrackedResource. func (tr TrackedResource) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if tr.Location != nil { objectMap["location"] = tr.Location } if tr.Tags != nil { objectMap["tags"] = tr.Tags } return json.Marshal(objectMap) } // TransparentDataEncryption represents a database transparent data encryption configuration. type TransparentDataEncryption struct { autorest.Response `json:"-"` // Location - READ-ONLY; Resource location. Location *string `json:"location,omitempty"` // TransparentDataEncryptionProperties - Represents the properties of the resource. *TransparentDataEncryptionProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for TransparentDataEncryption. func (tde TransparentDataEncryption) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if tde.TransparentDataEncryptionProperties != nil { objectMap["properties"] = tde.TransparentDataEncryptionProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for TransparentDataEncryption struct. func (tde *TransparentDataEncryption) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } tde.Location = &location } case "properties": if v != nil { var transparentDataEncryptionProperties TransparentDataEncryptionProperties err = json.Unmarshal(*v, &transparentDataEncryptionProperties) if err != nil { return err } tde.TransparentDataEncryptionProperties = &transparentDataEncryptionProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } tde.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } tde.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } tde.Type = &typeVar } } } return nil } // TransparentDataEncryptionActivity represents a database transparent data encryption Scan. type TransparentDataEncryptionActivity struct { // Location - READ-ONLY; Resource location. Location *string `json:"location,omitempty"` // TransparentDataEncryptionActivityProperties - Represents the properties of the resource. *TransparentDataEncryptionActivityProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for TransparentDataEncryptionActivity. func (tdea TransparentDataEncryptionActivity) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if tdea.TransparentDataEncryptionActivityProperties != nil { objectMap["properties"] = tdea.TransparentDataEncryptionActivityProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for TransparentDataEncryptionActivity struct. func (tdea *TransparentDataEncryptionActivity) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } tdea.Location = &location } case "properties": if v != nil { var transparentDataEncryptionActivityProperties TransparentDataEncryptionActivityProperties err = json.Unmarshal(*v, &transparentDataEncryptionActivityProperties) if err != nil { return err } tdea.TransparentDataEncryptionActivityProperties = &transparentDataEncryptionActivityProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } tdea.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } tdea.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } tdea.Type = &typeVar } } } return nil } // TransparentDataEncryptionActivityListResult represents the response to a list database transparent data // encryption activity request. type TransparentDataEncryptionActivityListResult struct { autorest.Response `json:"-"` // Value - The list of database transparent data encryption activities. Value *[]TransparentDataEncryptionActivity `json:"value,omitempty"` } // TransparentDataEncryptionActivityProperties represents the properties of a database transparent data // encryption Scan. type TransparentDataEncryptionActivityProperties struct { // Status - READ-ONLY; The status of the database. Possible values include: 'Encrypting', 'Decrypting' Status TransparentDataEncryptionActivityStatus `json:"status,omitempty"` // PercentComplete - READ-ONLY; The percent complete of the transparent data encryption scan for a database. PercentComplete *float64 `json:"percentComplete,omitempty"` } // TransparentDataEncryptionProperties represents the properties of a database transparent data encryption. type TransparentDataEncryptionProperties struct { // Status - The status of the database transparent data encryption. Possible values include: 'TransparentDataEncryptionStatusEnabled', 'TransparentDataEncryptionStatusDisabled' Status TransparentDataEncryptionStatus `json:"status,omitempty"` } // Usage ARM usage. type Usage struct { // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *Name `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` // Unit - READ-ONLY; Usage unit. Unit *string `json:"unit,omitempty"` // CurrentValue - READ-ONLY; Usage current value. CurrentValue *int32 `json:"currentValue,omitempty"` // Limit - READ-ONLY; Usage limit. Limit *int32 `json:"limit,omitempty"` // RequestedLimit - READ-ONLY; Usage requested limit. RequestedLimit *int32 `json:"requestedLimit,omitempty"` } // UsageListResult a list of usages. type UsageListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]Usage `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // UsageListResultIterator provides access to a complete listing of Usage values. type UsageListResultIterator struct { i int page UsageListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *UsageListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/UsageListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *UsageListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter UsageListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter UsageListResultIterator) Response() UsageListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter UsageListResultIterator) Value() Usage { if !iter.page.NotDone() { return Usage{} } return iter.page.Values()[iter.i] } // Creates a new instance of the UsageListResultIterator type. func NewUsageListResultIterator(page UsageListResultPage) UsageListResultIterator { return UsageListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (ulr UsageListResult) IsEmpty() bool { return ulr.Value == nil || len(*ulr.Value) == 0 } // usageListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (ulr UsageListResult) usageListResultPreparer(ctx context.Context) (*http.Request, error) { if ulr.NextLink == nil || len(to.String(ulr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(ulr.NextLink))) } // UsageListResultPage contains a page of Usage values. type UsageListResultPage struct { fn func(context.Context, UsageListResult) (UsageListResult, error) ulr UsageListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *UsageListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/UsageListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.ulr) if err != nil { return err } page.ulr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *UsageListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page UsageListResultPage) NotDone() bool { return !page.ulr.IsEmpty() } // Response returns the raw server response from the last page request. func (page UsageListResultPage) Response() UsageListResult { return page.ulr } // Values returns the slice of values for the current page or nil if there are no values. func (page UsageListResultPage) Values() []Usage { if page.ulr.IsEmpty() { return nil } return *page.ulr.Value } // Creates a new instance of the UsageListResultPage type. func NewUsageListResultPage(getNextPage func(context.Context, UsageListResult) (UsageListResult, error)) UsageListResultPage { return UsageListResultPage{fn: getNextPage} } // VirtualCluster an Azure SQL virtual cluster. type VirtualCluster struct { autorest.Response `json:"-"` // VirtualClusterProperties - Resource properties. *VirtualClusterProperties `json:"properties,omitempty"` // Location - Resource location. Location *string `json:"location,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for VirtualCluster. func (vc VirtualCluster) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if vc.VirtualClusterProperties != nil { objectMap["properties"] = vc.VirtualClusterProperties } if vc.Location != nil { objectMap["location"] = vc.Location } if vc.Tags != nil { objectMap["tags"] = vc.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for VirtualCluster struct. func (vc *VirtualCluster) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var virtualClusterProperties VirtualClusterProperties err = json.Unmarshal(*v, &virtualClusterProperties) if err != nil { return err } vc.VirtualClusterProperties = &virtualClusterProperties } case "location": if v != nil { var location string err = json.Unmarshal(*v, &location) if err != nil { return err } vc.Location = &location } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } vc.Tags = tags } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } vc.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } vc.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } vc.Type = &typeVar } } } return nil } // VirtualClusterListResult a list of virtual clusters. type VirtualClusterListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]VirtualCluster `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // VirtualClusterListResultIterator provides access to a complete listing of VirtualCluster values. type VirtualClusterListResultIterator struct { i int page VirtualClusterListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *VirtualClusterListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualClusterListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *VirtualClusterListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter VirtualClusterListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter VirtualClusterListResultIterator) Response() VirtualClusterListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter VirtualClusterListResultIterator) Value() VirtualCluster { if !iter.page.NotDone() { return VirtualCluster{} } return iter.page.Values()[iter.i] } // Creates a new instance of the VirtualClusterListResultIterator type. func NewVirtualClusterListResultIterator(page VirtualClusterListResultPage) VirtualClusterListResultIterator { return VirtualClusterListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (vclr VirtualClusterListResult) IsEmpty() bool { return vclr.Value == nil || len(*vclr.Value) == 0 } // virtualClusterListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (vclr VirtualClusterListResult) virtualClusterListResultPreparer(ctx context.Context) (*http.Request, error) { if vclr.NextLink == nil || len(to.String(vclr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(vclr.NextLink))) } // VirtualClusterListResultPage contains a page of VirtualCluster values. type VirtualClusterListResultPage struct { fn func(context.Context, VirtualClusterListResult) (VirtualClusterListResult, error) vclr VirtualClusterListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *VirtualClusterListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualClusterListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.vclr) if err != nil { return err } page.vclr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *VirtualClusterListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page VirtualClusterListResultPage) NotDone() bool { return !page.vclr.IsEmpty() } // Response returns the raw server response from the last page request. func (page VirtualClusterListResultPage) Response() VirtualClusterListResult { return page.vclr } // Values returns the slice of values for the current page or nil if there are no values. func (page VirtualClusterListResultPage) Values() []VirtualCluster { if page.vclr.IsEmpty() { return nil } return *page.vclr.Value } // Creates a new instance of the VirtualClusterListResultPage type. func NewVirtualClusterListResultPage(getNextPage func(context.Context, VirtualClusterListResult) (VirtualClusterListResult, error)) VirtualClusterListResultPage { return VirtualClusterListResultPage{fn: getNextPage} } // VirtualClusterProperties the properties of a virtual cluster. type VirtualClusterProperties struct { // SubnetID - READ-ONLY; Subnet resource ID for the virtual cluster. SubnetID *string `json:"subnetId,omitempty"` // Family - If the service has different generations of hardware, for the same SKU, then that can be captured here. Family *string `json:"family,omitempty"` // ChildResources - READ-ONLY; List of resources in this virtual cluster. ChildResources *[]string `json:"childResources,omitempty"` } // VirtualClustersDeleteFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type VirtualClustersDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *VirtualClustersDeleteFuture) Result(client VirtualClustersClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.VirtualClustersDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.VirtualClustersDeleteFuture") return } ar.Response = future.Response() return } // VirtualClustersUpdateFuture an abstraction for monitoring and retrieving the results of a long-running // operation. type VirtualClustersUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *VirtualClustersUpdateFuture) Result(client VirtualClustersClient) (vc VirtualCluster, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.VirtualClustersUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.VirtualClustersUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if vc.Response.Response, err = future.GetResult(sender); err == nil && vc.Response.Response.StatusCode != http.StatusNoContent { vc, err = client.UpdateResponder(vc.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.VirtualClustersUpdateFuture", "Result", vc.Response.Response, "Failure responding to request") } } return } // VirtualClusterUpdate an update request for an Azure SQL Database virtual cluster. type VirtualClusterUpdate struct { // VirtualClusterProperties - Resource properties. *VirtualClusterProperties `json:"properties,omitempty"` // Tags - Resource tags. Tags map[string]*string `json:"tags"` } // MarshalJSON is the custom marshaler for VirtualClusterUpdate. func (vcu VirtualClusterUpdate) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if vcu.VirtualClusterProperties != nil { objectMap["properties"] = vcu.VirtualClusterProperties } if vcu.Tags != nil { objectMap["tags"] = vcu.Tags } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for VirtualClusterUpdate struct. func (vcu *VirtualClusterUpdate) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var virtualClusterProperties VirtualClusterProperties err = json.Unmarshal(*v, &virtualClusterProperties) if err != nil { return err } vcu.VirtualClusterProperties = &virtualClusterProperties } case "tags": if v != nil { var tags map[string]*string err = json.Unmarshal(*v, &tags) if err != nil { return err } vcu.Tags = tags } } } return nil } // VirtualNetworkRule a virtual network rule. type VirtualNetworkRule struct { autorest.Response `json:"-"` // VirtualNetworkRuleProperties - Resource properties. *VirtualNetworkRuleProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for VirtualNetworkRule. func (vnr VirtualNetworkRule) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if vnr.VirtualNetworkRuleProperties != nil { objectMap["properties"] = vnr.VirtualNetworkRuleProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for VirtualNetworkRule struct. func (vnr *VirtualNetworkRule) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var virtualNetworkRuleProperties VirtualNetworkRuleProperties err = json.Unmarshal(*v, &virtualNetworkRuleProperties) if err != nil { return err } vnr.VirtualNetworkRuleProperties = &virtualNetworkRuleProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } vnr.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } vnr.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } vnr.Type = &typeVar } } } return nil } // VirtualNetworkRuleListResult a list of virtual network rules. type VirtualNetworkRuleListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]VirtualNetworkRule `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // VirtualNetworkRuleListResultIterator provides access to a complete listing of VirtualNetworkRule values. type VirtualNetworkRuleListResultIterator struct { i int page VirtualNetworkRuleListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *VirtualNetworkRuleListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkRuleListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *VirtualNetworkRuleListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter VirtualNetworkRuleListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter VirtualNetworkRuleListResultIterator) Response() VirtualNetworkRuleListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter VirtualNetworkRuleListResultIterator) Value() VirtualNetworkRule { if !iter.page.NotDone() { return VirtualNetworkRule{} } return iter.page.Values()[iter.i] } // Creates a new instance of the VirtualNetworkRuleListResultIterator type. func NewVirtualNetworkRuleListResultIterator(page VirtualNetworkRuleListResultPage) VirtualNetworkRuleListResultIterator { return VirtualNetworkRuleListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (vnrlr VirtualNetworkRuleListResult) IsEmpty() bool { return vnrlr.Value == nil || len(*vnrlr.Value) == 0 } // virtualNetworkRuleListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (vnrlr VirtualNetworkRuleListResult) virtualNetworkRuleListResultPreparer(ctx context.Context) (*http.Request, error) { if vnrlr.NextLink == nil || len(to.String(vnrlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(vnrlr.NextLink))) } // VirtualNetworkRuleListResultPage contains a page of VirtualNetworkRule values. type VirtualNetworkRuleListResultPage struct { fn func(context.Context, VirtualNetworkRuleListResult) (VirtualNetworkRuleListResult, error) vnrlr VirtualNetworkRuleListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *VirtualNetworkRuleListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VirtualNetworkRuleListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.vnrlr) if err != nil { return err } page.vnrlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *VirtualNetworkRuleListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page VirtualNetworkRuleListResultPage) NotDone() bool { return !page.vnrlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page VirtualNetworkRuleListResultPage) Response() VirtualNetworkRuleListResult { return page.vnrlr } // Values returns the slice of values for the current page or nil if there are no values. func (page VirtualNetworkRuleListResultPage) Values() []VirtualNetworkRule { if page.vnrlr.IsEmpty() { return nil } return *page.vnrlr.Value } // Creates a new instance of the VirtualNetworkRuleListResultPage type. func NewVirtualNetworkRuleListResultPage(getNextPage func(context.Context, VirtualNetworkRuleListResult) (VirtualNetworkRuleListResult, error)) VirtualNetworkRuleListResultPage { return VirtualNetworkRuleListResultPage{fn: getNextPage} } // VirtualNetworkRuleProperties properties of a virtual network rule. type VirtualNetworkRuleProperties struct { // VirtualNetworkSubnetID - The ARM resource id of the virtual network subnet. VirtualNetworkSubnetID *string `json:"virtualNetworkSubnetId,omitempty"` // IgnoreMissingVnetServiceEndpoint - Create firewall rule before the virtual network has vnet service endpoint enabled. IgnoreMissingVnetServiceEndpoint *bool `json:"ignoreMissingVnetServiceEndpoint,omitempty"` // State - READ-ONLY; Virtual Network Rule State. Possible values include: 'VirtualNetworkRuleStateInitializing', 'VirtualNetworkRuleStateInProgress', 'VirtualNetworkRuleStateReady', 'VirtualNetworkRuleStateDeleting', 'VirtualNetworkRuleStateUnknown' State VirtualNetworkRuleState `json:"state,omitempty"` } // VirtualNetworkRulesCreateOrUpdateFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type VirtualNetworkRulesCreateOrUpdateFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *VirtualNetworkRulesCreateOrUpdateFuture) Result(client VirtualNetworkRulesClient) (vnr VirtualNetworkRule, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.VirtualNetworkRulesCreateOrUpdateFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.VirtualNetworkRulesCreateOrUpdateFuture") return } sender := autorest.DecorateSender(client, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) if vnr.Response.Response, err = future.GetResult(sender); err == nil && vnr.Response.Response.StatusCode != http.StatusNoContent { vnr, err = client.CreateOrUpdateResponder(vnr.Response.Response) if err != nil { err = autorest.NewErrorWithError(err, "sql.VirtualNetworkRulesCreateOrUpdateFuture", "Result", vnr.Response.Response, "Failure responding to request") } } return } // VirtualNetworkRulesDeleteFuture an abstraction for monitoring and retrieving the results of a // long-running operation. type VirtualNetworkRulesDeleteFuture struct { azure.Future } // Result returns the result of the asynchronous operation. // If the operation has not completed it will return an error. func (future *VirtualNetworkRulesDeleteFuture) Result(client VirtualNetworkRulesClient) (ar autorest.Response, err error) { var done bool done, err = future.DoneWithContext(context.Background(), client) if err != nil { err = autorest.NewErrorWithError(err, "sql.VirtualNetworkRulesDeleteFuture", "Result", future.Response(), "Polling failure") return } if !done { err = azure.NewAsyncOpIncompleteError("sql.VirtualNetworkRulesDeleteFuture") return } ar.Response = future.Response() return } // VulnerabilityAssessmentRecurringScansProperties properties of a Vulnerability Assessment recurring // scans. type VulnerabilityAssessmentRecurringScansProperties struct { // IsEnabled - Recurring scans state. IsEnabled *bool `json:"isEnabled,omitempty"` // EmailSubscriptionAdmins - Specifies that the schedule scan notification will be is sent to the subscription administrators. EmailSubscriptionAdmins *bool `json:"emailSubscriptionAdmins,omitempty"` // Emails - Specifies an array of e-mail addresses to which the scan notification is sent. Emails *[]string `json:"emails,omitempty"` } // VulnerabilityAssessmentScanError properties of a vulnerability assessment scan error. type VulnerabilityAssessmentScanError struct { // Code - READ-ONLY; The error code. Code *string `json:"code,omitempty"` // Message - READ-ONLY; The error message. Message *string `json:"message,omitempty"` } // VulnerabilityAssessmentScanRecord a vulnerability assessment scan record. type VulnerabilityAssessmentScanRecord struct { autorest.Response `json:"-"` // VulnerabilityAssessmentScanRecordProperties - Resource properties. *VulnerabilityAssessmentScanRecordProperties `json:"properties,omitempty"` // ID - READ-ONLY; Resource ID. ID *string `json:"id,omitempty"` // Name - READ-ONLY; Resource name. Name *string `json:"name,omitempty"` // Type - READ-ONLY; Resource type. Type *string `json:"type,omitempty"` } // MarshalJSON is the custom marshaler for VulnerabilityAssessmentScanRecord. func (vasr VulnerabilityAssessmentScanRecord) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) if vasr.VulnerabilityAssessmentScanRecordProperties != nil { objectMap["properties"] = vasr.VulnerabilityAssessmentScanRecordProperties } return json.Marshal(objectMap) } // UnmarshalJSON is the custom unmarshaler for VulnerabilityAssessmentScanRecord struct. func (vasr *VulnerabilityAssessmentScanRecord) UnmarshalJSON(body []byte) error { var m map[string]*json.RawMessage err := json.Unmarshal(body, &m) if err != nil { return err } for k, v := range m { switch k { case "properties": if v != nil { var vulnerabilityAssessmentScanRecordProperties VulnerabilityAssessmentScanRecordProperties err = json.Unmarshal(*v, &vulnerabilityAssessmentScanRecordProperties) if err != nil { return err } vasr.VulnerabilityAssessmentScanRecordProperties = &vulnerabilityAssessmentScanRecordProperties } case "id": if v != nil { var ID string err = json.Unmarshal(*v, &ID) if err != nil { return err } vasr.ID = &ID } case "name": if v != nil { var name string err = json.Unmarshal(*v, &name) if err != nil { return err } vasr.Name = &name } case "type": if v != nil { var typeVar string err = json.Unmarshal(*v, &typeVar) if err != nil { return err } vasr.Type = &typeVar } } } return nil } // VulnerabilityAssessmentScanRecordListResult a list of vulnerability assessment scan records. type VulnerabilityAssessmentScanRecordListResult struct { autorest.Response `json:"-"` // Value - READ-ONLY; Array of results. Value *[]VulnerabilityAssessmentScanRecord `json:"value,omitempty"` // NextLink - READ-ONLY; Link to retrieve next page of results. NextLink *string `json:"nextLink,omitempty"` } // VulnerabilityAssessmentScanRecordListResultIterator provides access to a complete listing of // VulnerabilityAssessmentScanRecord values. type VulnerabilityAssessmentScanRecordListResultIterator struct { i int page VulnerabilityAssessmentScanRecordListResultPage } // NextWithContext advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. func (iter *VulnerabilityAssessmentScanRecordListResultIterator) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VulnerabilityAssessmentScanRecordListResultIterator.NextWithContext") defer func() { sc := -1 if iter.Response().Response.Response != nil { sc = iter.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } iter.i++ if iter.i < len(iter.page.Values()) { return nil } err = iter.page.NextWithContext(ctx) if err != nil { iter.i-- return err } iter.i = 0 return nil } // Next advances to the next value. If there was an error making // the request the iterator does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (iter *VulnerabilityAssessmentScanRecordListResultIterator) Next() error { return iter.NextWithContext(context.Background()) } // NotDone returns true if the enumeration should be started or is not yet complete. func (iter VulnerabilityAssessmentScanRecordListResultIterator) NotDone() bool { return iter.page.NotDone() && iter.i < len(iter.page.Values()) } // Response returns the raw server response from the last page request. func (iter VulnerabilityAssessmentScanRecordListResultIterator) Response() VulnerabilityAssessmentScanRecordListResult { return iter.page.Response() } // Value returns the current value or a zero-initialized value if the // iterator has advanced beyond the end of the collection. func (iter VulnerabilityAssessmentScanRecordListResultIterator) Value() VulnerabilityAssessmentScanRecord { if !iter.page.NotDone() { return VulnerabilityAssessmentScanRecord{} } return iter.page.Values()[iter.i] } // Creates a new instance of the VulnerabilityAssessmentScanRecordListResultIterator type. func NewVulnerabilityAssessmentScanRecordListResultIterator(page VulnerabilityAssessmentScanRecordListResultPage) VulnerabilityAssessmentScanRecordListResultIterator { return VulnerabilityAssessmentScanRecordListResultIterator{page: page} } // IsEmpty returns true if the ListResult contains no values. func (vasrlr VulnerabilityAssessmentScanRecordListResult) IsEmpty() bool { return vasrlr.Value == nil || len(*vasrlr.Value) == 0 } // vulnerabilityAssessmentScanRecordListResultPreparer prepares a request to retrieve the next set of results. // It returns nil if no more results exist. func (vasrlr VulnerabilityAssessmentScanRecordListResult) vulnerabilityAssessmentScanRecordListResultPreparer(ctx context.Context) (*http.Request, error) { if vasrlr.NextLink == nil || len(to.String(vasrlr.NextLink)) < 1 { return nil, nil } return autorest.Prepare((&http.Request{}).WithContext(ctx), autorest.AsJSON(), autorest.AsGet(), autorest.WithBaseURL(to.String(vasrlr.NextLink))) } // VulnerabilityAssessmentScanRecordListResultPage contains a page of VulnerabilityAssessmentScanRecord // values. type VulnerabilityAssessmentScanRecordListResultPage struct { fn func(context.Context, VulnerabilityAssessmentScanRecordListResult) (VulnerabilityAssessmentScanRecordListResult, error) vasrlr VulnerabilityAssessmentScanRecordListResult } // NextWithContext advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. func (page *VulnerabilityAssessmentScanRecordListResultPage) NextWithContext(ctx context.Context) (err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/VulnerabilityAssessmentScanRecordListResultPage.NextWithContext") defer func() { sc := -1 if page.Response().Response.Response != nil { sc = page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } next, err := page.fn(ctx, page.vasrlr) if err != nil { return err } page.vasrlr = next return nil } // Next advances to the next page of values. If there was an error making // the request the page does not advance and the error is returned. // Deprecated: Use NextWithContext() instead. func (page *VulnerabilityAssessmentScanRecordListResultPage) Next() error { return page.NextWithContext(context.Background()) } // NotDone returns true if the page enumeration should be started or is not yet complete. func (page VulnerabilityAssessmentScanRecordListResultPage) NotDone() bool { return !page.vasrlr.IsEmpty() } // Response returns the raw server response from the last page request. func (page VulnerabilityAssessmentScanRecordListResultPage) Response() VulnerabilityAssessmentScanRecordListResult { return page.vasrlr } // Values returns the slice of values for the current page or nil if there are no values. func (page VulnerabilityAssessmentScanRecordListResultPage) Values() []VulnerabilityAssessmentScanRecord { if page.vasrlr.IsEmpty() { return nil } return *page.vasrlr.Value } // Creates a new instance of the VulnerabilityAssessmentScanRecordListResultPage type. func NewVulnerabilityAssessmentScanRecordListResultPage(getNextPage func(context.Context, VulnerabilityAssessmentScanRecordListResult) (VulnerabilityAssessmentScanRecordListResult, error)) VulnerabilityAssessmentScanRecordListResultPage { return VulnerabilityAssessmentScanRecordListResultPage{fn: getNextPage} } // VulnerabilityAssessmentScanRecordProperties properties of a vulnerability assessment scan record. type VulnerabilityAssessmentScanRecordProperties struct { // ScanID - READ-ONLY; The scan ID. ScanID *string `json:"scanId,omitempty"` // TriggerType - READ-ONLY; The scan trigger type. Possible values include: 'VulnerabilityAssessmentScanTriggerTypeOnDemand', 'VulnerabilityAssessmentScanTriggerTypeRecurring' TriggerType VulnerabilityAssessmentScanTriggerType `json:"triggerType,omitempty"` // State - READ-ONLY; The scan status. Possible values include: 'VulnerabilityAssessmentScanStatePassed', 'VulnerabilityAssessmentScanStateFailed', 'VulnerabilityAssessmentScanStateFailedToRun', 'VulnerabilityAssessmentScanStateInProgress' State VulnerabilityAssessmentScanState `json:"state,omitempty"` // StartTime - READ-ONLY; The scan start time (UTC). StartTime *date.Time `json:"startTime,omitempty"` // EndTime - READ-ONLY; The scan end time (UTC). EndTime *date.Time `json:"endTime,omitempty"` // Errors - READ-ONLY; The scan errors. Errors *[]VulnerabilityAssessmentScanError `json:"errors,omitempty"` // StorageContainerPath - READ-ONLY; The scan results storage container path. StorageContainerPath *string `json:"storageContainerPath,omitempty"` // NumberOfFailedSecurityChecks - READ-ONLY; The number of failed security checks. NumberOfFailedSecurityChecks *int32 `json:"numberOfFailedSecurityChecks,omitempty"` }
PossibleJobStepOutputTypeValues
SVG.js
document.getElementById("id_business_version").innerHTML = "Business version = 2017.11.27.1"; window.addEventListener("deviceorientation",on_device_orientation); //----------------------------------------- function deseneaza_cerc(unghi1,unghi2) { var cerc = document.getElementById("id_circle"); cerc.setAttribute("cx",200+unghi1*200/90); cerc.setAttribute("cy",200+unghi2*200/90); } //------------------------------------ function on_device_orientation(e)
{ deseneaza_cerc(e.gamma,e.beta); }
newDataAnalytics.py
import json import web import calendar import datetime import cloudserver urls = ( "/BuildingFootprint/", "BuildingFootprint", "/BuildingFootprintDisaggregated/", "BuildingFootprintDisaggregated", "/PersonalConsumption/", "PersonalConsumption", "/HistoricalConsumption/", "HistoricalConsumption") class BuildingFootprint: def GET(self): raw_time = web.input() if "end" not in raw_time: end = calendar.timegm(datetime.datetime.utcnow().utctimetuple()) else: end = float(raw_time['end']) if "start" not in raw_time: start = calendar.timegm(datetime.datetime.utcnow().utctimetuple())-24*60*60 #1 day else: start = float(raw_time['start']) return cloudserver.db.buildingFootprint(start, end) class
: def GET(self): raw_time = web.input() if "end" not in raw_time: end = calendar.timegm(datetime.datetime.utcnow().utctimetuple()) else: end = float(raw_time['end']) if "start" not in raw_time: start = calendar.timegm(datetime.datetime.utcnow().utctimetuple())-24*60*60 #1 day else: start = float(raw_time['start']) return cloudserver.db.buildingFootprintDisaggregated(start, end) class PersonalConsumption: def GET(self): print("Got to Personal Consumption") raw_data = web.input() end = calendar.timegm(datetime.datetime.utcnow().utctimetuple()) if "end" in raw_data: end = float(raw_data['end']) start = calendar.timegm(datetime.datetime.utcnow().utctimetuple())-24*60*60 #1 day if "start" in raw_data: start = float(raw_data['start']) user = "Peter Wei" if "user" in raw_data: user = raw_data['user'] return cloudserver.db.personalFootprint(user, start, end) class HistoricalConsumption: def GET(self): return cloudserver.db.historicalConsumption() dataExtraction = web.application(urls, locals())
BuildingFootprintDisaggregated
problem-02.js
function
(worker) { if(worker.handsShaking === true) { worker.bloodAlcoholLevel += (worker.weight * 0.1) * worker.experience; worker.handsShaking = false; } return worker; }
solve
test_models_wheel.py
import pytest from pip._vendor.packaging.tags import Tag from pip._internal import pep425tags from pip._internal.exceptions import InvalidWheelFilename from pip._internal.models.wheel import Wheel class TestWheelFile(object): def test_std_wheel_pattern(self): w = Wheel('simple-1.1.1-py2-none-any.whl') assert w.name == 'simple' assert w.version == '1.1.1' assert w.pyversions == ['py2'] assert w.abis == ['none'] assert w.plats == ['any'] def test_wheel_pattern_multi_values(self): w = Wheel('simple-1.1-py2.py3-abi1.abi2-any.whl') assert w.name == 'simple' assert w.version == '1.1' assert w.pyversions == ['py2', 'py3'] assert w.abis == ['abi1', 'abi2'] assert w.plats == ['any'] def test_wheel_with_build_tag(self): # pip doesn't do anything with build tags, but theoretically, we might # see one, in this case the build tag = '4' w = Wheel('simple-1.1-4-py2-none-any.whl') assert w.name == 'simple' assert w.version == '1.1' assert w.pyversions == ['py2'] assert w.abis == ['none'] assert w.plats == ['any'] def test_single_digit_version(self): w = Wheel('simple-1-py2-none-any.whl') assert w.version == '1' def test_non_pep440_version(self): w = Wheel('simple-_invalid_-py2-none-any.whl') assert w.version == '-invalid-' def test_missing_version_raises(self): with pytest.raises(InvalidWheelFilename): Wheel('Cython-cp27-none-linux_x86_64.whl') def test_invalid_filename_raises(self): with pytest.raises(InvalidWheelFilename): Wheel('invalid.whl') def test_supported_single_version(self): """ Test single-version wheel is known to be supported """ w = Wheel('simple-0.1-py2-none-any.whl') assert w.supported(tags=[Tag('py2', 'none', 'any')]) def test_supported_multi_version(self): """ Test multi-version wheel is known to be supported """ w = Wheel('simple-0.1-py2.py3-none-any.whl') assert w.supported(tags=[Tag('py3', 'none', 'any')]) def test_not_supported_version(self): """ Test unsupported wheel is known to be unsupported """ w = Wheel('simple-0.1-py2-none-any.whl') assert not w.supported(tags=[Tag('py1', 'none', 'any')]) def test_supported_osx_version(self): """ Wheels built for macOS 10.6 are supported on 10.9 """ tags = pep425tags.get_supported( '27', platform='macosx_10_9_intel', impl='cp' ) w = Wheel('simple-0.1-cp27-none-macosx_10_6_intel.whl') assert w.supported(tags=tags) w = Wheel('simple-0.1-cp27-none-macosx_10_9_intel.whl') assert w.supported(tags=tags) def test_not_supported_osx_version(self):
def test_supported_multiarch_darwin(self): """ Multi-arch wheels (intel) are supported on components (i386, x86_64) """ universal = pep425tags.get_supported( '27', platform='macosx_10_5_universal', impl='cp' ) intel = pep425tags.get_supported( '27', platform='macosx_10_5_intel', impl='cp' ) x64 = pep425tags.get_supported( '27', platform='macosx_10_5_x86_64', impl='cp' ) i386 = pep425tags.get_supported( '27', platform='macosx_10_5_i386', impl='cp' ) ppc = pep425tags.get_supported( '27', platform='macosx_10_5_ppc', impl='cp' ) ppc64 = pep425tags.get_supported( '27', platform='macosx_10_5_ppc64', impl='cp' ) w = Wheel('simple-0.1-cp27-none-macosx_10_5_intel.whl') assert w.supported(tags=intel) assert w.supported(tags=x64) assert w.supported(tags=i386) assert not w.supported(tags=universal) assert not w.supported(tags=ppc) assert not w.supported(tags=ppc64) w = Wheel('simple-0.1-cp27-none-macosx_10_5_universal.whl') assert w.supported(tags=universal) assert w.supported(tags=intel) assert w.supported(tags=x64) assert w.supported(tags=i386) assert w.supported(tags=ppc) assert w.supported(tags=ppc64) def test_not_supported_multiarch_darwin(self): """ Single-arch wheels (x86_64) are not supported on multi-arch (intel) """ universal = pep425tags.get_supported( '27', platform='macosx_10_5_universal', impl='cp' ) intel = pep425tags.get_supported( '27', platform='macosx_10_5_intel', impl='cp' ) w = Wheel('simple-0.1-cp27-none-macosx_10_5_i386.whl') assert not w.supported(tags=intel) assert not w.supported(tags=universal) w = Wheel('simple-0.1-cp27-none-macosx_10_5_x86_64.whl') assert not w.supported(tags=intel) assert not w.supported(tags=universal) def test_support_index_min(self): """ Test results from `support_index_min` """ tags = [ Tag('py2', 'none', 'TEST'), Tag('py2', 'TEST', 'any'), Tag('py2', 'none', 'any'), ] w = Wheel('simple-0.1-py2-none-any.whl') assert w.support_index_min(tags=tags) == 2 w = Wheel('simple-0.1-py2-none-TEST.whl') assert w.support_index_min(tags=tags) == 0 def test_support_index_min__none_supported(self): """ Test a wheel not supported by the given tags. """ w = Wheel('simple-0.1-py2-none-any.whl') with pytest.raises(ValueError): w.support_index_min(tags=[]) def test_version_underscore_conversion(self): """ Test that we convert '_' to '-' for versions parsed out of wheel filenames """ w = Wheel('simple-0.1_1-py2-none-any.whl') assert w.version == '0.1-1'
""" Wheels built for macOS 10.9 are not supported on 10.6 """ tags = pep425tags.get_supported( '27', platform='macosx_10_6_intel', impl='cp' ) w = Wheel('simple-0.1-cp27-none-macosx_10_9_intel.whl') assert not w.supported(tags=tags)
status_server_test.go
/* Copyright 2021 The CI/CD Operator Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package blocker import ( "encoding/json" "fmt" "github.com/bmizerany/assert" cicdv1 "github.com/tmax-cloud/cicd-operator/api/v1" "io/ioutil" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "net/http" "net/http/httptest" "os" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/log/zap" "testing" ) func TestBlocker_statusServer(t *testing.T)
func statusServerTestConfig() client.Client { if _, exist := os.LookupEnv("CI"); !exist { ctrl.SetLogger(zap.New(zap.UseDevMode(true))) } s := runtime.NewScheme() utilruntime.Must(cicdv1.AddToScheme(s)) return fake.NewClientBuilder().WithScheme(s).Build() }
{ cli := statusServerTestConfig() b := New(cli) b.Pools["api.github.com/tmax-cloud/cicd-operator"] = NewPRPool(testICNamespace, testICName) srv := httptest.NewServer(b.newRouter()) // TEST 1 resp, err := http.Get(fmt.Sprintf("%s/status", srv.URL)) if err != nil { t.Fatal(err) } resultBytes, _ := ioutil.ReadAll(resp.Body) var result []statusListEntity if err := json.Unmarshal(resultBytes, &result); err != nil { t.Fatal(err) } assert.Equal(t, 200, resp.StatusCode, "Successful request") assert.Equal(t, 1, len(result), "One result pool") // TEST 2 resp, err = http.Get(fmt.Sprintf("%s/status/api.github.com/tmax-cloud/cicd-operator", srv.URL)) if err != nil { t.Fatal(err) } resultBytes, _ = ioutil.ReadAll(resp.Body) t.Log(string(resultBytes)) assert.Equal(t, 200, resp.StatusCode, "Successful request") }
caillprocess_temp_pickledlist.py
import time, copy import os, os.path import sys import numpy from PyQt4.QtCore import * from PyQt4.QtGui import * from scipy import optimize
p='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/2012-9FeCoNiTi_500C_CAill_plate1_dlist.dat' savefolder='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/2012-9FeCoNiTi_500C_CAill_plate1_illgraphs' os.chdir(savefolder) f=open(p, mode='r') dlist=pickle.load(f) f.close() o=numpy.ones(500, dtype='float32') z=numpy.zeros(500, dtype='float32') tocat=[z] for i in range(15): tocat+=[o, z] ill=numpy.concatenate(tocat) #darkinds=numpy.arange(90, 490) #illinds=numpy.arange(590, 990) darkinds=numpy.arange(290, 490) illinds=numpy.arange(790, 990) darkinds_cyc=[darkinds+i*1000 for i in range(16)] illinds_cyc=[illinds+i*1000 for i in range(15)] darkindsplot=numpy.arange(0, 500) illindsplot=numpy.arange(500, 1000) darkindsplot_cyc=[darkinds+i*1000 for i in range(16)] illindsplot_cyc=[illinds+i*1000 for i in range(15)] getdarkvals=lambda arr:numpy.array([arr[inds].mean() for inds in darkinds_cyc]) getillvals=lambda arr:numpy.array([arr[inds].mean() for inds in illinds_cyc]) o500=numpy.ones(500, dtype='float32') t_ill=getillvals(dlist[0]['t(s)']) pylab.figure() for d in dlist: if d['Sample']!=1164: continue if len(d['I(A)'])<15500: print 'problem with sample ', d['Sample'] d['Photocurrent(A)']=numpy.nan d['Photocurrent_std(A)']=numpy.nan d['Photocurrent_cycs(A)']=numpy.nan continue i_ill=getillvals(d['I(A)']) i_dark=getdarkvals(d['I(A)']) idiff=i_ill-0.5*(i_dark[:-1]+i_dark[1:]) d['Photocurrent(A)']=idiff.mean() d['Photocurrent_std(A)']=idiff.std() d['Photocurrent_cycs(A)']=idiff pylab.clf() ax=pylab.subplot(111) ax2=ax.twinx() ax.plot(d['t(s)'], d['I(A)']) d['I(A)_SG']=savgolsmooth(d['I(A)'], nptsoneside=50, order = 2) ax.plot(d['t(s)'], d['I(A)_SG'], 'k') ax2.plot(t_ill, idiff, 'ro') iplt=numpy.concatenate([numpy.concatenate([dv*o500, di*o500]) for dv, di in zip(i_dark, i_ill)]+[i_dark[-1]*o500]) d['till_cycs']=t_ill d['Idiff_time']=iplt ax.plot(d['t(s)'], iplt, 'g') s=`d['Sample']`+', ' for el, v in zip(d['elements'], d['compositions']): s+=el+'%d' %(100*v) pylab.title(s) pylab.savefig('SecondAnalysis_'+`d['Sample']`) break #getdarkstd=lambda arr:numpy.array([arr[inds].std() for inds in darkinds_cyc]) #getillstd=lambda arr:numpy.array([arr[inds].std() for inds in illinds_cyc]) #i_darkstd=getdarkstd(d['I(A)_SG']) #i_illstd=getillstd(d['I(A)_SG']) #idiffstd=(i_illstd**2+0.25*(i_darkstd[:-1]**2+i_darkstd[1:]**2))**.5 #print idiffstd/idiff if 1: import pickle fld, fn=os.path.split(p) savep=os.path.join(os.path.join(fld, 'echemplots'), fn[:-4]+'_%d.dat' %d['Sample']) f=open(savep, mode='w') pickle.dump(d, f) f.close() pylab.show()
from echem_plate_ui import * from echem_plate_math import * import pickle
_bayesian_regression.py
import numpy as np from prml.linear._regression import Regression class BayesianRegression(Regression):
"""Bayesian regression model. w ~ N(w|0, alpha^(-1)I) y = X @ w t ~ N(t|X @ w, beta^(-1)) """ def __init__(self, alpha: float = 1.0, beta: float = 1.0): """Initialize bayesian linear regression model. Parameters ---------- alpha : float, optional Precision parameter of the prior, by default 1. beta : float, optional Precision parameter of the likelihood, by default 1. """ self.alpha = alpha self.beta = beta self.w_mean = None self.w_precision = None def _is_prior_defined(self) -> bool: return self.w_mean is not None and self.w_precision is not None def _get_prior(self, ndim: int) -> tuple: if self._is_prior_defined(): return self.w_mean, self.w_precision else: return np.zeros(ndim), self.alpha * np.eye(ndim) def fit(self, x_train: np.ndarray, y_train: np.ndarray): """Bayesian update of parameters given training dataset. Parameters ---------- x_train : np.ndarray training data independent variable (N, n_features) y_train : np.ndarray training data dependent variable """ mean_prev, precision_prev = self._get_prior(np.size(x_train, 1)) w_precision = precision_prev + self.beta * x_train.T @ x_train w_mean = np.linalg.solve( w_precision, precision_prev @ mean_prev + self.beta * x_train.T @ y_train, ) self.w_mean = w_mean self.w_precision = w_precision self.w_cov = np.linalg.inv(self.w_precision) def predict( self, x: np.ndarray, return_std: bool = False, sample_size: int = None, ): """Return mean (and standard deviation) of predictive distribution. Parameters ---------- x : np.ndarray independent variable (N, n_features) return_std : bool, optional flag to return standard deviation (the default is False) sample_size : int, optional number of samples to draw from the predictive distribution (the default is None, no sampling from the distribution) Returns ------- y : np.ndarray mean of the predictive distribution (N,) y_std : np.ndarray standard deviation of the predictive distribution (N,) y_sample : np.ndarray samples from the predictive distribution (N, sample_size) """ if sample_size is not None: w_sample = np.random.multivariate_normal( self.w_mean, self.w_cov, size=sample_size, ) y_sample = x @ w_sample.T return y_sample y = x @ self.w_mean if return_std: y_var = 1 / self.beta + np.sum(x @ self.w_cov * x, axis=1) y_std = np.sqrt(y_var) return y, y_std return y
main.rs
use bevy::prelude::*; use bevy::ui::Val::Px; fn main() { App::new() .add_plugins(DefaultPlugins) .insert_resource(ClearColor(Color::rgb_u8(48, 44, 44))) .insert_resource(WindowDescriptor { title: "Gerrymandering".to_string(), width: 1280.0, height: 720.0, resizable: false, ..Default::default() }) .insert_resource(Selected { pos: Vec::new() }) .insert_resource(Selection { selections: Vec::new(), }) .add_startup_system(startup) .add_system(mouse_click) .run(); } #[derive(Component)] struct Points { pos: (u16, u16), // this will be like x and y so it starts at the bottom left color: u8, // 0: blue, 1: red } #[derive(Component)] struct Selected { pos: Vec<(u8, u8)>, } #[derive(Component)] struct Selection { selections: Vec<(Vec<(u8, u8)>, u8)>, } #[derive(Component)] struct Lines; #[derive(Component)] struct DeleteText; #[derive(Component)] struct PermLines; static mut CURRENT_XY: (u8, u8) = (0, 0); static MAX: u16 = 600; static LINE_THINKNESS: f32 = 5.0; static mut LEVEL: u8 = 1; static mut GO_FOR: u8 = 0; fn startup(mut commands: Commands, server: Res<AssetServer>) { commands.spawn_bundle(OrthographicCameraBundle::new_2d()); commands.spawn_bundle(UiCameraBundle::default()); commands.spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new(-650.0, 0.0, 0.0), scale: Vec3::new(10.0, 750.0, 1.0), ..Default::default() }, sprite: Sprite { color: Color::rgb(0.0, 1.0, 0.0), ..Default::default() }, ..Default::default() }); commands.spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new(650.0, 0.0, 0.0), scale: Vec3::new(10.0, 750.0, 1.0), ..Default::default() }, sprite: Sprite { color: Color::rgb(0.0, 1.0, 0.0), ..Default::default() }, ..Default::default() }); commands.spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new(0.0, 370.0, 0.0), scale: Vec3::new(1310.0, 10.0, 1.0), ..Default::default() }, sprite: Sprite { color: Color::rgb(0.0, 1.0, 0.0), ..Default::default() }, ..Default::default() }); commands.spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new(0.0, -370.0, 0.0), scale: Vec3::new(1310.0, 10.0, 1.0), ..Default::default() }, sprite: Sprite { color: Color::rgb(0.0, 1.0, 0.0), ..Default::default() }, ..Default::default() }); commands .spawn_bundle(TextBundle { style: Style { position_type: PositionType::Absolute, position: Rect { bottom: Px(110.0), left: Px(225.0), ..Default::default() }, ..Default::default() }, text: Text::with_section( "Done", TextStyle { font: server.load("font/troika.otf"), font_size: 100.0, color: Color::WHITE, }, TextAlignment { horizontal: HorizontalAlign::Center, vertical: VerticalAlign::Center, }, ), ..Default::default() }); commands.spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new(-320.0, -200.0, 0.0), scale: Vec3::new(1.0, 1.0, 1.0), ..Default::default() }, texture: server.load("button_back.png"), ..Default::default() }); unsafe { CURRENT_XY = (((LEVEL / 2) * 2) + 3, ((LEVEL / 2) * 2) + 3); } spawn_points(make_points(), commands, server); } fn mouse_click( mouse_input: Res<Input<MouseButton>>, windows: Res<Windows>, mut commands: Commands, commands1: Commands, mut selected: ResMut<Selected>, mut selection: ResMut<Selection>, lines: Query<Entity, With<Lines>>, perm_lines: Query<Entity, With<PermLines>>, points_entity: Query<Entity, With<Points>>, points: Query<&Points>, server: Res<AssetServer>, delete_text: Query<Entity, With<DeleteText>>, ) { unsafe {
let mut redraw_selected = false; let mut redraw_selection = false; let size = ( MAX as f32 / (CURRENT_XY.0) as f32, MAX as f32 / (CURRENT_XY.1) as f32, ); if mouse_input.pressed(MouseButton::Left) { let pos = win.cursor_position().unwrap() - Vec2::new(win.width() / 2.0, win.height() / 2.0); if selection.selections.len() as u8 == CURRENT_XY.1 && pos.x > -570.0 && pos.x < -70.0 && pos.y > -350.0 && pos.y < -50.0 { let mut colors = 0; for x in &selection.selections { colors += x.1; } if (GO_FOR == 0 && (colors as f32) < (CURRENT_XY.1 as f32) / 2.0) || (GO_FOR == 1 && (colors as f32) > (CURRENT_XY.1 as f32) / 2.0) { for i in perm_lines.iter() { commands.entity(i).despawn(); } for i in lines.iter() { commands.entity(i).despawn(); } for i in points_entity.iter() { commands.entity(i).despawn(); } for i in delete_text.iter() { commands.entity(i).despawn(); } selected.pos = Vec::new(); selection.selections = Vec::new(); LEVEL += 1; CURRENT_XY = (((LEVEL / 2) * 2) + 3, ((LEVEL / 2) * 2) + 3); spawn_points(make_points(), commands1, server); redraw_selected = true; redraw_selection = true; } } let mut has_selected_that_can_not = false; for i in &selection.selections { if i.0.contains(&( ((pos.x as f32 + 20.0) / size.0).ceil() as u8, ((pos.y as f32 + 300.0) / size.1).ceil() as u8, )) { has_selected_that_can_not = true; } } if ((pos.x as f32 + 20.0) / size.0).ceil() <= CURRENT_XY.0 as f32 && ((pos.x as f32 + 20.0) / size.0).ceil() > 0.0 && ((pos.y as f32 + 300.0) / size.1).ceil() <= CURRENT_XY.1 as f32 && ((pos.y as f32 + 300.0) / size.1).ceil() > 0.0 && !selected.pos.contains(&( ((pos.x as f32 + 20.0) / size.0).ceil() as u8, ((pos.y as f32 + 300.0) / size.1).ceil() as u8, )) && selected.pos.len() < CURRENT_XY.1 as usize && !has_selected_that_can_not { selected.pos.push(( ((pos.x as f32 + 20.0) / size.0).ceil() as u8, ((pos.y as f32 + 300.0) / size.1).ceil() as u8, )); redraw_selected = true; } if selected.pos.clone().len() == CURRENT_XY.1 as usize { let mut ammount_of_red = 0; for i in points.iter() { if selected .pos .contains(&(i.pos.0 as u8 + 1, i.pos.1 as u8 + 1)) { ammount_of_red += i.color; } } selection.selections.push(( selected.pos.clone(), if ammount_of_red as f32 > selected.pos.len() as f32 / 2.0 { 1 } else { 0 }, )); selected.pos = Vec::new(); redraw_selection = true; } } if mouse_input.pressed(MouseButton::Right) { let pos = win.cursor_position().unwrap() - Vec2::new(win.width() / 2.0, win.height() / 2.0); if ((pos.x as f32 + 20.0) / size.0).ceil() <= CURRENT_XY.0 as f32 && ((pos.x as f32 + 20.0) / size.0).ceil() > 0.0 && ((pos.y as f32 + 300.0) / size.1).ceil() <= CURRENT_XY.1 as f32 && ((pos.y as f32 + 300.0) / size.1).ceil() > 0.0 { let mut stop = false; if selected.pos.contains(&( ((pos.x as f32 + 20.0) / size.0).ceil() as u8, ((pos.y as f32 + 300.0) / size.1).ceil() as u8, )) { for i in 0..selected.pos.len() { if !stop { if selected.pos.get(i).unwrap() == &( ((pos.x as f32 + 20.0) / size.0).ceil() as u8, ((pos.y as f32 + 300.0) / size.1).ceil() as u8, ) { selected.pos.remove(i); redraw_selected = true; stop = true; } } } } stop = false; for i in 0..selection.selections.len() { if !stop { if selection.selections.get(i).unwrap().0.contains(&( ((pos.x as f32 + 20.0) / size.0).ceil() as u8, ((pos.y as f32 + 300.0) / size.1).ceil() as u8, )) { selection.selections.remove(i); redraw_selection = true; stop = true; } } } } } if redraw_selected { for i in lines.iter() { commands.entity(i).despawn(); } for i in &selected.pos { if !selected.pos.contains(&(i.0 - 1, i.1)) { commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( (i.0 as f32 - 1.0) * size.0 - 20.0, (i.1 as f32 - 1.0) * size.1 + size.1 / 2.0 - 300.0, 0.0, ), scale: Vec3::new( LINE_THINKNESS, size.1 + LINE_THINKNESS / 2.0, 0.0, ), ..Default::default() }, sprite: Sprite { color: Color::rgb(1.0, 1.0, 1.0), ..Default::default() }, ..Default::default() }) .insert(Lines); } if !selected.pos.contains(&(i.0 + 1, i.1)) { commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( (i.0 as f32 - 1.0) * size.0 + size.0 - 20.0, (i.1 as f32 - 1.0) * size.1 + size.1 / 2.0 - 300.0, 0.0, ), scale: Vec3::new( LINE_THINKNESS, size.1 + LINE_THINKNESS / 2.0, 0.0, ), ..Default::default() }, sprite: Sprite { color: Color::rgb(1.0, 1.0, 1.0), ..Default::default() }, ..Default::default() }) .insert(Lines); } if !selected.pos.contains(&(i.0, i.1 - 1)) { commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( (i.0 as f32 - 1.0) * size.0 + size.0 / 2.0 - 20.0, (i.1 as f32 - 1.0) * size.1 - 300.0, 0.0, ), scale: Vec3::new( size.0 + LINE_THINKNESS / 2.0, LINE_THINKNESS, 0.0, ), ..Default::default() }, sprite: Sprite { color: Color::rgb(1.0, 1.0, 1.0), ..Default::default() }, ..Default::default() }) .insert(Lines); } if !selected.pos.contains(&(i.0, i.1 + 1)) { commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( (i.0 as f32 - 1.0) * size.0 + size.0 / 2.0 - 20.0, (i.1 as f32 - 1.0) * size.1 + size.1 - 300.0, 0.0, ), scale: Vec3::new( size.0 + LINE_THINKNESS / 2.0, LINE_THINKNESS, 0.0, ), ..Default::default() }, sprite: Sprite { color: Color::rgb(1.0, 1.0, 1.0), ..Default::default() }, ..Default::default() }) .insert(Lines); } commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( (i.0 as f32 - 1.0) * size.0 + size.0 / 2.0 - 20.0, (i.1 as f32 - 1.0) * size.1 + size.1 / 2.0 - 300.0, 1.0, ), scale: Vec3::new(size.0, size.1, 0.0), ..Default::default() }, sprite: Sprite { color: Color::rgba(1.0, 1.0, 1.0, 0.01), ..Default::default() }, ..Default::default() }) .insert(Lines); } } if redraw_selection { for i in perm_lines.iter() { commands.entity(i).despawn(); } for i in &selection.selections { for x in &i.0 { if !i.0.contains(&(x.0 - 1, x.1)) { commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( (x.0 as f32 - 1.0) * size.0 - 20.0, (x.1 as f32 - 1.0) * size.1 + size.1 / 2.0 - 300.0, 0.0, ), scale: Vec3::new( LINE_THINKNESS, size.1 + LINE_THINKNESS / 2.0, 0.0, ), ..Default::default() }, sprite: Sprite { color: Color::rgb_u8(169, 169, 169), ..Default::default() }, ..Default::default() }) .insert(PermLines); } if !i.0.contains(&(x.0 + 1, x.1)) { commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( (x.0 as f32 - 1.0) * size.0 + size.0 - 20.0, (x.1 as f32 - 1.0) * size.1 + size.1 / 2.0 - 300.0, 0.0, ), scale: Vec3::new( LINE_THINKNESS, size.1 + LINE_THINKNESS / 2.0, 0.0, ), ..Default::default() }, sprite: Sprite { color: Color::rgb_u8(169, 169, 169), ..Default::default() }, ..Default::default() }) .insert(PermLines); } if !i.0.contains(&(x.0, x.1 - 1)) { commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( (x.0 as f32 - 1.0) * size.0 + size.0 / 2.0 - 20.0, (x.1 as f32 - 1.0) * size.1 - 300.0, 0.0, ), scale: Vec3::new( size.0 + LINE_THINKNESS / 2.0, LINE_THINKNESS, 0.0, ), ..Default::default() }, sprite: Sprite { color: Color::rgb_u8(169, 169, 169), ..Default::default() }, ..Default::default() }) .insert(PermLines); } if !i.0.contains(&(x.0, x.1 + 1)) { commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( (x.0 as f32 - 1.0) * size.0 + size.0 / 2.0 - 20.0, (x.1 as f32 - 1.0) * size.1 + size.1 - 300.0, 0.0, ), scale: Vec3::new( size.0 + LINE_THINKNESS / 2.0, LINE_THINKNESS, 0.0, ), ..Default::default() }, sprite: Sprite { color: Color::rgb_u8(169, 169, 169), ..Default::default() }, ..Default::default() }) .insert(PermLines); } commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( (x.0 as f32 - 1.0) * size.0 + size.0 / 2.0 - 20.0, (x.1 as f32 - 1.0) * size.1 + size.1 / 2.0 - 300.0, 1.0, ), scale: Vec3::new(size.0, size.1, 0.0), ..Default::default() }, sprite: match i.1 { 0 => Sprite { color: Color::rgba_u8(33, 91, 166, 128), ..Default::default() }, _ => Sprite { color: Color::rgba_u8(166, 36, 47, 128), ..Default::default() }, }, ..Default::default() }) .insert(PermLines); } } } } } fn make_points() -> Vec<Points> { unsafe { // this will be better but you know idc let mut output: Vec<Points> = Vec::new(); for x in 0..CURRENT_XY.0 { for y in 0..CURRENT_XY.1 { output.push(Points { pos: (x.into(), y.into()), color: (rand::random::<f32>() * 2.0).floor() as u8, }) } } let mut ammount_of_red = 0; for i in &output { ammount_of_red += i.color; } while (ammount_of_red as f32) > (CURRENT_XY.0 * CURRENT_XY.1) as f32 / 5.0 * 3.0 || (ammount_of_red as f32) < (CURRENT_XY.0 * CURRENT_XY.1) as f32 / 5.0 * 2.0 { output = Vec::new(); for x in 0..CURRENT_XY.0 { for y in 0..CURRENT_XY.1 { output.push(Points { pos: (x.into(), y.into()), color: (rand::random::<f32>() * 2.0).floor() as u8, }) } } ammount_of_red = 0; for i in &output { ammount_of_red += i.color; } } GO_FOR = if (ammount_of_red as f32) > (CURRENT_XY.0 * CURRENT_XY.1) as f32 / 2.0 { 0 } else if (ammount_of_red as f32) < (CURRENT_XY.0 * CURRENT_XY.1) as f32 / 2.0 { 1 } else { (rand::random::<f32>() * 2.0).floor() as u8 }; output } } fn spawn_points( x: Vec<Points>, mut commands: Commands, server: Res<AssetServer>, ) { unsafe { let size = ( MAX as f32 / (CURRENT_XY.0) as f32, MAX as f32 / (CURRENT_XY.1) as f32, ); for i in &x { commands .spawn_bundle(SpriteBundle { transform: Transform { translation: Vec3::new( i.pos.0 as f32 * size.0 + size.0 / 2.0 - 20.0, i.pos.1 as f32 * size.1 + size.1 / 2.0 - 300.0, 0.0, ), scale: Vec3::new(size.0 * 0.8 / 1024.0, size.1 * 0.8 / 1024.0, 1.0), ..Default::default() }, texture: match i.color { 0 => server.load("blue.png"), 1 => server.load("red.png"), _ => server.load("cant happen so lest error it out"), }, ..Default::default() }) .insert(Points { pos: i.pos, color: i.color, }); } commands .spawn_bundle(TextBundle { style: Style { position_type: PositionType::Absolute, position: Rect { top: Px(50.0), left: Px(50.0), ..Default::default() }, ..Default::default() }, text: Text::with_section( format!("Level: {}", LEVEL), TextStyle { font: server.load("font/troika.otf"), font_size: 100.0, color: Color::WHITE, }, TextAlignment { horizontal: HorizontalAlign::Center, vertical: VerticalAlign::Center, }, ), ..Default::default() }) .insert(DeleteText); commands .spawn_bundle(TextBundle { style: Style { position_type: PositionType::Absolute, position: Rect { top: Px(175.0), left: Px(50.0), ..Default::default() }, ..Default::default() }, text: Text::with_section( match GO_FOR { 0 => "Try and make\n blue win", _ => "Try and make\n red win", }, TextStyle { font: server.load("font/troika.otf"), font_size: 100.0, color: Color::WHITE, }, TextAlignment { horizontal: HorizontalAlign::Center, vertical: VerticalAlign::Center, }, ), ..Default::default() }) .insert(DeleteText); } }
let win = windows.get_primary().expect("no primary window");
main_page.py
#!/usr/bin/python3 import os import view book_types = os.listdir('books') data = os.listdir('data') if not data: import db db.create_tables(book_types) view.__main_page__(book_types)
else: import db db.check_for_update(book_types) view.__main_page__(book_types, data=True)
foundation.drilldown.js
'use strict'; !function($) { /** * Drilldown module. * @module foundation.drilldown * @requires foundation.util.keyboard * @requires foundation.util.motion * @requires foundation.util.nest */ class
{ /** * Creates a new instance of a drilldown menu. * @class * @param {jQuery} element - jQuery object to make into an accordion menu. * @param {Object} options - Overrides to the default plugin settings. */ constructor(element, options) { this.$element = element; this.options = $.extend({}, Drilldown.defaults, this.$element.data(), options); Foundation.Nest.Feather(this.$element, 'drilldown'); this._init(); Foundation.registerPlugin(this, 'Drilldown'); Foundation.Keyboard.register('Drilldown', { 'ENTER': 'open', 'SPACE': 'open', 'ARROW_RIGHT': 'next', 'ARROW_UP': 'up', 'ARROW_DOWN': 'down', 'ARROW_LEFT': 'previous', 'ESCAPE': 'close', 'TAB': 'down', 'SHIFT_TAB': 'up' }); } /** * Initializes the drilldown by creating jQuery collections of elements * @private */ _init() { this.$submenuAnchors = this.$element.find('li.is-drilldown-submenu-parent').children('a'); this.$submenus = this.$submenuAnchors.parent('li').children('[data-submenu]'); this.$menuItems = this.$element.find('li').not('.js-drilldown-back').attr('role', 'menuitem').find('a'); this._prepareMenu(); this._keyboardEvents(); } /** * prepares drilldown menu by setting attributes to links and elements * sets a min height to prevent content jumping * wraps the element if not already wrapped * @private * @function */ _prepareMenu() { var _this = this; // if(!this.options.holdOpen){ // this._menuLinkEvents(); // } this.$submenuAnchors.each(function(){ var $sub = $(this); var $link = $sub.find('a:first'); if(_this.options.parentLink){ $link.clone().prependTo($sub.children('[data-submenu]')).wrap('<li class="is-submenu-parent-item is-submenu-item is-drilldown-submenu-item" role="menu-item"></li>'); } $link.data('savedHref', $link.attr('href')).removeAttr('href'); $sub.children('[data-submenu]') .attr({ 'aria-hidden': true, 'tabindex': 0, 'role': 'menu' }); _this._events($sub); }); this.$submenus.each(function(){ var $menu = $(this), $back = $menu.find('.js-drilldown-back'); if(!$back.length){ $menu.prepend(_this.options.backButton); } _this._back($menu); }); if(!this.$element.parent().hasClass('is-drilldown')){ this.$wrapper = $(this.options.wrapper).addClass('is-drilldown').css(this._getMaxDims()); this.$element.wrap(this.$wrapper); } } /** * Adds event handlers to elements in the menu. * @function * @private * @param {jQuery} $elem - the current menu item to add handlers to. */ _events($elem) { var _this = this; $elem.off('click.zf.drilldown') .on('click.zf.drilldown', function(e){ if($(e.target).parentsUntil('ul', 'li').hasClass('is-drilldown-submenu-parent')){ e.stopImmediatePropagation(); e.preventDefault(); } // if(e.target !== e.currentTarget.firstElementChild){ // return false; // } _this._show($elem.parent('li')); if(_this.options.closeOnClick){ var $body = $('body').not(_this.$wrapper); $body.off('.zf.drilldown').on('click.zf.drilldown', function(e){ e.preventDefault(); _this._hideAll(); $body.off('.zf.drilldown'); }); } }); } /** * Adds keydown event listener to `li`'s in the menu. * @private */ _keyboardEvents() { var _this = this; this.$menuItems.add(this.$element.find('.js-drilldown-back > a')).on('keydown.zf.drilldown', function(e){ var $element = $(this), $elements = $element.parent('li').parent('ul').children('li').children('a'), $prevElement, $nextElement; $elements.each(function(i) { if ($(this).is($element)) { $prevElement = $elements.eq(Math.max(0, i-1)); $nextElement = $elements.eq(Math.min(i+1, $elements.length-1)); return; } }); Foundation.Keyboard.handleKey(e, 'Drilldown', { next: function() { if ($element.is(_this.$submenuAnchors)) { _this._show($element.parent('li')); $element.parent('li').one(Foundation.transitionend($element), function(){ $element.parent('li').find('ul li a').filter(_this.$menuItems).first().focus(); }); e.preventDefault(); } }, previous: function() { _this._hide($element.parent('li').parent('ul')); $element.parent('li').parent('ul').one(Foundation.transitionend($element), function(){ setTimeout(function() { $element.parent('li').parent('ul').parent('li').children('a').first().focus(); }, 1); }); e.preventDefault(); }, up: function() { $prevElement.focus(); e.preventDefault(); }, down: function() { $nextElement.focus(); e.preventDefault(); }, close: function() { _this._back(); //_this.$menuItems.first().focus(); // focus to first element }, open: function() { if (!$element.is(_this.$menuItems)) { // not menu item means back button _this._hide($element.parent('li').parent('ul')); $element.parent('li').parent('ul').one(Foundation.transitionend($element), function(){ setTimeout(function() { $element.parent('li').parent('ul').parent('li').children('a').first().focus(); }, 1); }); e.preventDefault(); } else if ($element.is(_this.$submenuAnchors)) { _this._show($element.parent('li')); $element.parent('li').one(Foundation.transitionend($element), function(){ $element.parent('li').find('ul li a').filter(_this.$menuItems).first().focus(); }); e.preventDefault(); } }, handled: function() { e.stopImmediatePropagation(); } }); }); // end keyboardAccess } /** * Closes all open elements, and returns to root menu. * @function * @fires Drilldown#closed */ _hideAll() { var $elem = this.$element.find('.is-drilldown-submenu.is-active').addClass('is-closing'); $elem.one(Foundation.transitionend($elem), function(e){ $elem.removeClass('is-active is-closing'); }); /** * Fires when the menu is fully closed. * @event Drilldown#closed */ this.$element.trigger('closed.zf.drilldown'); } /** * Adds event listener for each `back` button, and closes open menus. * @function * @fires Drilldown#back * @param {jQuery} $elem - the current sub-menu to add `back` event. */ _back($elem) { var _this = this; $elem.off('click.zf.drilldown'); $elem.children('.js-drilldown-back') .on('click.zf.drilldown', function(e){ e.stopImmediatePropagation(); // console.log('mouseup on back'); _this._hide($elem); }); } /** * Adds event listener to menu items w/o submenus to close open menus on click. * @function * @private */ _menuLinkEvents() { var _this = this; this.$menuItems.not('.is-drilldown-submenu-parent') .off('click.zf.drilldown') .on('click.zf.drilldown', function(e){ // e.stopImmediatePropagation(); setTimeout(function(){ _this._hideAll(); }, 0); }); } /** * Opens a submenu. * @function * @fires Drilldown#open * @param {jQuery} $elem - the current element with a submenu to open, i.e. the `li` tag. */ _show($elem) { $elem.children('[data-submenu]').addClass('is-active'); this.$element.trigger('open.zf.drilldown', [$elem]); }; /** * Hides a submenu * @function * @fires Drilldown#hide * @param {jQuery} $elem - the current sub-menu to hide, i.e. the `ul` tag. */ _hide($elem) { var _this = this; $elem.addClass('is-closing') .one(Foundation.transitionend($elem), function(){ $elem.removeClass('is-active is-closing'); $elem.blur(); }); /** * Fires when the submenu is has closed. * @event Drilldown#hide */ $elem.trigger('hide.zf.drilldown', [$elem]); } /** * Iterates through the nested menus to calculate the min-height, and max-width for the menu. * Prevents content jumping. * @function * @private */ _getMaxDims() { var max = 0, result = {}; this.$submenus.add(this.$element).each(function(){ var numOfElems = $(this).children('li').length; max = numOfElems > max ? numOfElems : max; }); result['min-height'] = `${max * this.$menuItems[0].getBoundingClientRect().height}px`; result['max-width'] = `${this.$element[0].getBoundingClientRect().width}px`; return result; } /** * Destroys the Drilldown Menu * @function */ destroy() { this._hideAll(); Foundation.Nest.Burn(this.$element, 'drilldown'); this.$element.unwrap() .find('.js-drilldown-back, .is-submenu-parent-item').remove() .end().find('.is-active, .is-closing, .is-drilldown-submenu').removeClass('is-active is-closing is-drilldown-submenu') .end().find('[data-submenu]').removeAttr('aria-hidden tabindex role') .off('.zf.drilldown').end().off('zf.drilldown'); this.$element.find('a').each(function(){ var $link = $(this); if($link.data('savedHref')){ $link.attr('href', $link.data('savedHref')).removeData('savedHref'); }else{ return; } }); Foundation.unregisterPlugin(this); }; } Drilldown.defaults = { /** * Markup used for JS generated back button. Prepended to submenu lists and deleted on `destroy` method, 'js-drilldown-back' class required. Remove the backslash (`\`) if copy and pasting. * @option * @example '<\li><\a>Back<\/a><\/li>' */ backButton: '<li class="js-drilldown-back"><a tabindex="0">Back</a></li>', /** * Markup used to wrap drilldown menu. Use a class name for independent styling; the JS applied class: `is-drilldown` is required. Remove the backslash (`\`) if copy and pasting. * @option * @example '<\div class="is-drilldown"><\/div>' */ wrapper: '<div></div>', /** * Adds the parent link to the submenu. * @option * @example false */ parentLink: false, /** * Allow the menu to return to root list on body click. * @option * @example false */ closeOnClick: false // holdOpen: false }; // Window exports Foundation.plugin(Drilldown, 'Drilldown'); }(jQuery);
Drilldown
_configuration.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license 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 if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential VERSION = "unknown" class ApplicationInsightsManagementClientConfiguration(Configuration): """Configuration for ApplicationInsightsManagementClient. 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",
) -> 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(ApplicationInsightsManagementClientConfiguration, self).__init__(**kwargs) self.credential = credential self.subscription_id = subscription_id self.api_version = "2019-09-01-preview" self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default']) kwargs.setdefault('sdk_moniker', 'mgmt-applicationinsights/{}'.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)
subscription_id: str, **kwargs: Any
gsubr.go
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package riscv import ( "cmd/compile/internal/gc"
func ginsnop() { // Hardware nop is ADD $0, ZERO p := gc.Prog(riscv.AADD) p.From.Type = obj.TYPE_CONST p.From3 = &obj.Addr{Type: obj.TYPE_REG, Reg: riscv.REG_ZERO} p.To = *p.From3 }
"cmd/internal/obj" "cmd/internal/obj/riscv" )
test_cron.py
import os import datetime from nose.exc import SkipTest from nose.tools import eq_ import mock from django.conf import settings import amo import amo.tests from addons import cron from addons.models import Addon, AppSupport from django.core.management.base import CommandError from files.models import File, Platform from lib.es.utils import flag_reindexing_amo, unflag_reindexing_amo from stats.models import UpdateCount from versions.models import Version class CurrentVersionTestCase(amo.tests.TestCase): fixtures = ['base/addon_3615'] @mock.patch('waffle.switch_is_active', lambda x: True) def test_addons(self): Addon.objects.filter(pk=3615).update(_current_version=None) eq_(Addon.objects.filter(_current_version=None, pk=3615).count(), 1) cron._update_addons_current_version(((3615,),)) eq_(Addon.objects.filter(_current_version=None, pk=3615).count(), 0) @mock.patch('waffle.switch_is_active', lambda x: True) def test_cron(self): Addon.objects.filter(pk=3615).update(_current_version=None) eq_(Addon.objects.filter(_current_version=None, pk=3615).count(), 1) cron.update_addons_current_version() eq_(Addon.objects.filter(_current_version=None, pk=3615).count(), 0) class TestLastUpdated(amo.tests.TestCase): fixtures = ['base/addon_3615', 'addons/listed', 'base/apps', 'addons/persona', 'base/seamonkey', 'base/thunderbird'] def test_personas(self): Addon.objects.update(type=amo.ADDON_PERSONA, status=amo.STATUS_PUBLIC) cron.addon_last_updated() for addon in Addon.objects.all(): eq_(addon.last_updated, addon.created) # Make sure it's stable. cron.addon_last_updated() for addon in Addon.objects.all(): eq_(addon.last_updated, addon.created) def test_catchall(self): """Make sure the catch-all last_updated is stable and accurate.""" # Nullify all datestatuschanged so the public add-ons hit the # catch-all. (File.objects.filter(status=amo.STATUS_PUBLIC) .update(datestatuschanged=None)) Addon.objects.update(last_updated=None) cron.addon_last_updated() for addon in Addon.objects.filter(status=amo.STATUS_PUBLIC, type=amo.ADDON_EXTENSION): eq_(addon.last_updated, addon.created) # Make sure it's stable. cron.addon_last_updated() for addon in Addon.objects.filter(status=amo.STATUS_PUBLIC): eq_(addon.last_updated, addon.created) def test_last_updated_lite(self): # Make sure lite addons' last_updated matches their file's # datestatuschanged. Addon.objects.update(status=amo.STATUS_LITE, last_updated=None) File.objects.update(status=amo.STATUS_LITE) cron.addon_last_updated() addon = Addon.objects.get(id=3615) files = File.objects.filter(version__addon=addon) eq_(len(files), 1) eq_(addon.last_updated, files[0].datestatuschanged) assert addon.last_updated def test_last_update_lite_no_files(self): Addon.objects.update(status=amo.STATUS_LITE, last_updated=None) File.objects.update(status=amo.STATUS_UNREVIEWED) cron.addon_last_updated() addon = Addon.objects.get(id=3615) eq_(addon.last_updated, addon.created) assert addon.last_updated def test_appsupport(self): ids = Addon.objects.values_list('id', flat=True) cron._update_appsupport(ids) eq_(AppSupport.objects.filter(app=amo.FIREFOX.id).count(), 4) # Run it again to test deletes. cron._update_appsupport(ids) eq_(AppSupport.objects.filter(app=amo.FIREFOX.id).count(), 4) def test_appsupport_listed(self): AppSupport.objects.all().delete() eq_(AppSupport.objects.filter(addon=3723).count(), 0) cron.update_addon_appsupport() eq_(AppSupport.objects.filter(addon=3723, app=amo.FIREFOX.id).count(), 0) def test_appsupport_seamonkey(self): addon = Addon.objects.get(pk=15663) addon.update(status=amo.STATUS_PUBLIC) AppSupport.objects.all().delete() cron.update_addon_appsupport() eq_(AppSupport.objects.filter(addon=15663, app=amo.SEAMONKEY.id).count(), 1) class TestHideDisabledFiles(amo.tests.TestCase): msg = 'Moving disabled file: %s => %s' def setUp(self): p = Platform.objects.create(id=amo.PLATFORM_ALL.id) self.addon = Addon.objects.create(type=amo.ADDON_EXTENSION) self.version = Version.objects.create(addon=self.addon) self.f1 = File.objects.create(version=self.version, platform=p, filename='f1') self.f2 = File.objects.create(version=self.version, filename='f2', platform=p) @mock.patch('files.models.os') def
(self, os_mock): # All these addon/file status pairs should stay. stati = [(amo.STATUS_PUBLIC, amo.STATUS_PUBLIC), (amo.STATUS_PUBLIC, amo.STATUS_UNREVIEWED), (amo.STATUS_PUBLIC, amo.STATUS_BETA), (amo.STATUS_LITE, amo.STATUS_UNREVIEWED), (amo.STATUS_LITE, amo.STATUS_LITE), (amo.STATUS_LITE_AND_NOMINATED, amo.STATUS_UNREVIEWED), (amo.STATUS_LITE_AND_NOMINATED, amo.STATUS_LITE)] for addon_status, file_status in stati: self.addon.update(status=addon_status) File.objects.update(status=file_status) cron.hide_disabled_files() assert not os_mock.path.exists.called, (addon_status, file_status) @mock.patch('files.models.File.mv') @mock.patch('files.models.storage') def test_move_user_disabled_addon(self, m_storage, mv_mock): # Use Addon.objects.update so the signal handler isn't called. Addon.objects.filter(id=self.addon.id).update( status=amo.STATUS_PUBLIC, disabled_by_user=True) File.objects.update(status=amo.STATUS_PUBLIC) cron.hide_disabled_files() # Check that f2 was moved. f2 = self.f2 mv_mock.assert_called_with(f2.file_path, f2.guarded_file_path, self.msg) m_storage.delete.assert_called_with(f2.mirror_file_path) # Check that f1 was moved as well. f1 = self.f1 mv_mock.call_args = mv_mock.call_args_list[0] m_storage.delete.call_args = m_storage.delete.call_args_list[0] mv_mock.assert_called_with(f1.file_path, f1.guarded_file_path, self.msg) m_storage.delete.assert_called_with(f1.mirror_file_path) # There's only 2 files, both should have been moved. eq_(mv_mock.call_count, 2) eq_(m_storage.delete.call_count, 2) @mock.patch('files.models.File.mv') @mock.patch('files.models.storage') def test_move_admin_disabled_addon(self, m_storage, mv_mock): Addon.objects.filter(id=self.addon.id).update( status=amo.STATUS_DISABLED) File.objects.update(status=amo.STATUS_PUBLIC) cron.hide_disabled_files() # Check that f2 was moved. f2 = self.f2 mv_mock.assert_called_with(f2.file_path, f2.guarded_file_path, self.msg) m_storage.delete.assert_called_with(f2.mirror_file_path) # Check that f1 was moved as well. f1 = self.f1 mv_mock.call_args = mv_mock.call_args_list[0] m_storage.delete.call_args = m_storage.delete.call_args_list[0] mv_mock.assert_called_with(f1.file_path, f1.guarded_file_path, self.msg) m_storage.delete.assert_called_with(f1.mirror_file_path) # There's only 2 files, both should have been moved. eq_(mv_mock.call_count, 2) eq_(m_storage.delete.call_count, 2) @mock.patch('files.models.File.mv') @mock.patch('files.models.storage') def test_move_disabled_file(self, m_storage, mv_mock): Addon.objects.filter(id=self.addon.id).update(status=amo.STATUS_LITE) File.objects.filter(id=self.f1.id).update(status=amo.STATUS_DISABLED) File.objects.filter(id=self.f2.id).update(status=amo.STATUS_UNREVIEWED) cron.hide_disabled_files() # Only f1 should have been moved. f1 = self.f1 mv_mock.assert_called_with(f1.file_path, f1.guarded_file_path, self.msg) eq_(mv_mock.call_count, 1) # It should have been removed from mirror stagins. m_storage.delete.assert_called_with(f1.mirror_file_path) eq_(m_storage.delete.call_count, 1) class AvgDailyUserCountTestCase(amo.tests.TestCase): fixtures = ['base/addon_3615'] def test_adu_is_adjusted_in_cron(self): addon = Addon.objects.get(pk=3615) self.assertTrue( addon.average_daily_users > addon.total_downloads + 10000, 'Unexpected ADU count. ADU of %d not greater than %d' % ( addon.average_daily_users, addon.total_downloads + 10000)) cron._update_addon_average_daily_users([(3615, 6000000)]) addon = Addon.objects.get(pk=3615) eq_(addon.average_daily_users, addon.total_downloads) def test_adu_flag(self): addon = Addon.objects.get(pk=3615) now = datetime.datetime.now() counter = UpdateCount.objects.create(addon=addon, date=now, count=1234) counter.save() self.assertTrue( addon.average_daily_users > addon.total_downloads + 10000, 'Unexpected ADU count. ADU of %d not greater than %d' % ( addon.average_daily_users, addon.total_downloads + 10000)) adu = cron.update_addon_average_daily_users flag_reindexing_amo('new', 'old', 'alias') try: # Should fail. self.assertRaises(CommandError, adu) # Should work with the environ flag. os.environ['FORCE_INDEXING'] = '1' adu() finally: unflag_reindexing_amo() del os.environ['FORCE_INDEXING'] addon = Addon.objects.get(pk=3615) eq_(addon.average_daily_users, 1234)
test_leave_nondisabled_files
x_full_no_current_collector.py
# # Class for full thermal submodel # import pybamm from .base_x_full import BaseModel class NoCurrentCollector(BaseModel): """Class for full x-direction thermal submodel without current collectors Parameters ---------- param : parameter class The parameters to use for this submodel **Extends:** :class:`pybamm.thermal.x_full.BaseModel` """ def __init__(self, param): super().__init__(param) def set_rhs(self, variables): T = variables["Cell temperature"] q = variables["Heat flux"] Q = variables["Total heating"] self.rhs = { T: (-pybamm.div(q) / self.param.delta ** 2 + self.param.B * Q) / (self.param.C_th * self.param.rho_k) } def set_boundary_conditions(self, variables):
T_amb = variables["Ambient temperature"] self.boundary_conditions = { T: { "left": ( self.param.h * (T_n_left - T_amb) / self.param.lambda_n, "Neumann", ), "right": ( -self.param.h * (T_p_right - T_amb) / self.param.lambda_p, "Neumann", ), } } def _current_collector_heating(self, variables): """Returns zeros for current collector heat source terms""" Q_s_cn = pybamm.Scalar(0) Q_s_cp = pybamm.Scalar(0) return Q_s_cn, Q_s_cp def _yz_average(self, var): """ Computes the y-z average by integration over y and z In this case this is just equal to the input variable """ return var def _x_average(self, var, var_cn, var_cp): """ Computes the X-average over the whole cell *not* including current collectors. This overwrites the default behaviour of 'base_thermal'. """ return pybamm.x_average(var)
T = variables["Cell temperature"] T_n_left = pybamm.boundary_value(T, "left") T_p_right = pybamm.boundary_value(T, "right")
error.py
from json import loads from ..models.response import ErrorMessage class WebsiteContactsApiError(Exception): def __init__(self, message): self.message = message @property def message(self): return self._message @message.setter def message(self, message): self._message = message def __str__(self): return str(self.__dict__) class ParameterError(WebsiteContactsApiError): pass class EmptyApiKeyError(WebsiteContactsApiError): pass class ResponseError(WebsiteContactsApiError): def __init__(self, message): self.message = message
self.parsed_message = ErrorMessage(parsed) except Exception: pass @property def parsed_message(self): return self._parsed_message @parsed_message.setter def parsed_message(self, pm): self._parsed_message = pm class UnparsableApiResponseError(WebsiteContactsApiError): def __init__(self, message, origin_error): self.message = message self.original_error = origin_error @property def original_error(self): return self._original_error @original_error.setter def original_error(self, oe): self._original_error = oe class ApiAuthError(ResponseError): pass class BadRequestError(ResponseError): pass class HttpApiError(WebsiteContactsApiError): pass
self._parsed_message = None try: parsed = loads(message)
synthesis.rs
#![allow(dead_code)] //! We have a set of constant vectors. //! //! For the number of constraints n: //! For the number of source terms s: //! Create n * s variables representing source constraint i in n applying to source term j in s. //! For each source vector: //! Create a variable representing that arrangement, and condition the following clauses on that //! variable //! For each forbidden constant vector: //! Create a cause table for that constant vector given the sources. //! For each cause, create a cnf clause requiring one of the constraints between two of the //! non-equal source terms //! For each required constant vector: //! Create a cause table for that constant vector given the sources. //! For each cause, create a variable representing that cause being responsible for the //! constant vector. //! Create a cnf clause requiring either that cause is not responsible, or none of the //! constraints prevent that cause from operating. //! Require that at least one of the causes is responsible for the constant vector. use cryptominisat::{Lbool, Lit, Solver}; use fact_table::{FactTable, PredicateFactIter}; use program::Program; use std::collections::HashSet; use std::collections::hash_map::{Entry, HashMap}; use std::iter::repeat; use std::sync::Arc; use std::time::Instant; use truth_value::TruthValue; use types::{Clause, Constant, Fact, Literal, Predicate, Term}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct Source { predicate: Predicate, term_idx: usize, } pub struct SourceVecIter<'a, T> where T: 'a + TruthValue { sources: Arc<Vec<Source>>, minimum_num_sources: usize, maximum_num_sources: usize, program: &'a Program<T>, } impl<'a, T> Iterator for SourceVecIter<'a, T> where T: 'a + TruthValue { type Item = Arc<Vec<Source>>; fn next(&mut self) -> Option<Self::Item> { { let sources = Arc::make_mut(&mut self.sources); if sources.len() < self.minimum_num_sources { *sources = repeat(Source { predicate: 0, term_idx: 0, }) .take(self.minimum_num_sources) .collect(); } else { let num_sources: usize = sources.len(); for i in (0..num_sources).rev() { { let source = &mut sources[i]; if source.term_idx + 1 < self.program.get_num_terms(source.predicate) { source.term_idx += 1; break; } else if source.predicate + 1 < self.program.num_predicates() { source.term_idx = 0; source.predicate += 1; break; } else { source.term_idx = 0; source.predicate = 0; if i > 0 { continue; } } } if num_sources < self.maximum_num_sources { sources.push(Source { predicate: 0, term_idx: 0, }); } else { return None; } } } } Some(self.sources.clone()) } } impl<'a, T> SourceVecIter<'a, T> where T: 'a + TruthValue { fn new(minimum_num_sources: usize, maximum_num_sources: usize, program: &'a Program<T>) -> Self { SourceVecIter { sources: Arc::new(Vec::new()), program, minimum_num_sources, maximum_num_sources, } } } struct ConstantVecIter<'p, 'f, T> where T: 'p + 'f + TruthValue { source_iter: SourceVecIter<'p, T>, state: Option<(Arc<Vec<Source>>, FactsFromSources<'f, T>)>, fact_table: &'f FactTable<T>, } impl<'p, 'f, T> ConstantVecIter<'p, 'f, T> where T: 'p + 'f + TruthValue { pub fn new(minimum_num_sources: usize, maximum_num_sources: usize, program: &'p Program<T>, fact_table: &'f FactTable<T>) -> Self { ConstantVecIter { source_iter: SourceVecIter::new(minimum_num_sources, maximum_num_sources, program), state: None, fact_table, } } } impl<'p, 'f, T> Iterator for ConstantVecIter<'p, 'f, T> where T: 'p + 'f + TruthValue { type Item = (Arc<Vec<Source>>, Arc<Vec<&'f Fact>>); fn next(&mut self) -> Option<Self::Item> { if let Some((ref sources, ref mut constants_iter)) = self.state { if let Some(facts) = constants_iter.next() { return Some((sources.clone(), facts)); } } while let Some(sources) = self.source_iter.next() { if let Some(facts_iter) = FactsFromSources::from_sources(sources.clone(), self.fact_table) { self.state = Some((sources, facts_iter)); return self.next(); } } return None; } } struct FactsFromSources<'f, T> where T: 'f + TruthValue { sources: Arc<Vec<Source>>, fact_table: &'f FactTable<T>, fact_iters: Vec<PredicateFactIter<'f, T>>, facts: Arc<Vec<&'f Fact>>, skip_update: bool, } impl<'f, T> FactsFromSources<'f, T> where T: 'f + TruthValue { fn from_sources(sources: Arc<Vec<Source>>, fact_table: &'f FactTable<T>) -> Option<Self> { let mut facts = Vec::new(); let mut fact_iters = Vec::new(); for source in sources.iter() { let mut fact_iter = fact_table.predicate_facts(source.predicate); if let Some((fact, _truth)) = fact_iter.next() { facts.push(fact); fact_iters.push(fact_iter); } else { return None; } } Some(FactsFromSources { sources, fact_table, fact_iters, facts: Arc::new(facts), skip_update: true, }) } } impl<'f, T> Iterator for FactsFromSources<'f, T> where T: 'f + TruthValue { type Item = Arc<Vec<&'f Fact>>; fn next(&mut self) -> Option<Self::Item> { let mut should_return_facts = false; if !self.skip_update { let facts = Arc::make_mut(&mut self.facts); for i in (0..self.fact_iters.len()).rev() { if let Some((fact, _truth)) = self.fact_iters[i].next() { facts[i] = fact; should_return_facts = true; break; } else if i > 0 { self.fact_iters[i] = self.fact_table .predicate_facts(self.sources[i].predicate); } } } else { self.skip_update = false; should_return_facts = true; } if should_return_facts { return Some(self.facts.clone()); } else { return None; } } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct SourceTerm { source_idx: usize, term_idx: usize, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct EqualityConstraint(SourceTerm, SourceTerm); fn constant_vec_from_sources_facts(sources: &[Source], facts: &[&Fact]) -> Vec<Constant> { let mut result = Vec::new(); for (source, fact) in sources.iter().zip(facts) { result.push(fact.terms[source.term_idx]); } return result; } fn violated_constraint_literals(solver: &mut Solver, equality_constraints: &mut HashMap<EqualityConstraint, Lit>, facts: &[&Fact]) -> Vec<Lit> { let mut result = Vec::new(); for (source_idx_a, fact_a) in facts.iter().enumerate() { for (source_idx_b, fact_b) in facts.iter().enumerate().skip(source_idx_a) { for (term_idx_a, a) in fact_a.terms.iter().enumerate() { let to_skip; if source_idx_a == source_idx_b { to_skip = term_idx_a + 1; } else { to_skip = 0; } for (term_idx_b, b) in fact_b.terms.iter().enumerate().skip(to_skip) { if a != b { let source_term_a = SourceTerm { source_idx: source_idx_a, term_idx: term_idx_a, }; let source_term_b = SourceTerm { source_idx: source_idx_b, term_idx: term_idx_b, }; let constraint = EqualityConstraint(source_term_a, source_term_b); let lit = match equality_constraints.entry(constraint) { Entry::Occupied(pair) => pair.get().clone(), Entry::Vacant(pair) => pair.insert(solver.new_var()).clone(), }; result.push(lit); } } } } } return result; } struct SynthesisState { source_permutation_vars: HashMap<Vec<Source>, Lit>, equality_constraint_vars: HashMap<EqualityConstraint, Lit>, solver: Solver, } impl SynthesisState { fn new() -> Self { let mut solver = Solver::new(); solver.set_num_threads(4); SynthesisState { source_permutation_vars: HashMap::new(), equality_constraint_vars: HashMap::new(), solver, } } fn require_constant_vector<T>(&mut self, required: &[Constant], forbidden: &HashSet<Vec<Constant>>, program: &Program<T>, facts: &FactTable<T>, min_sources: usize, max_sources: usize) where T: TruthValue { let start_of_source_iteration = Instant::now(); for sources in SourceVecIter::new(min_sources, max_sources, program) { let use_sources = match self.source_permutation_vars .entry(sources.as_ref().clone()) { Entry::Occupied(entry) => entry.get().clone(), Entry::Vacant(entry) => entry.insert(self.solver.new_var()).clone(), }; let mut had_required = false; if let Some(facts_iter) = FactsFromSources::from_sources(sources.clone(), facts) { for facts in facts_iter { let violated_constraints = violated_constraint_literals(&mut self.solver, &mut self.equality_constraint_vars, &facts); let constant_vec = constant_vec_from_sources_facts(&sources, &facts); let constant_vec_prefix = &constant_vec[0..required.len()]; if required == constant_vec_prefix { // if use_sources, no violated EqualityConstraint for constraint_lit in violated_constraints.iter() { // Either: // - Don't use the source // - Don't violate the constraint self.solver .add_clause(&[!use_sources, !constraint_lit.clone()]); } had_required = true; } if forbidden.contains(constant_vec_prefix) { let mut clause = violated_constraints; if clause.len() == 0 { self.solver.add_clause(&[!use_sources]); break; } else { clause.push(!use_sources); // Either: // - Don't use the source // - Violate one of the constraints self.solver.add_clause(&clause); } } } } if !had_required { self.solver.add_clause(&[!use_sources]); } } println!("number of variables: {}", self.solver.nvars()); println!("source iteration took {} seconds", start_of_source_iteration.elapsed().as_secs()); } fn
(mut self) -> Option<(Vec<Source>, Vec<EqualityConstraint>)> { if self.source_permutation_vars.len() == 0 { return None; } let use_at_least_one_set_of_sources = self.source_permutation_vars .iter() .map(|(_, &lit)| lit) .collect::<Vec<_>>(); self.solver.add_clause(&use_at_least_one_set_of_sources); let start_of_solving = Instant::now(); let solve_result = self.solver.solve(); println!("solving took {} seconds", start_of_solving.elapsed().as_secs()); if solve_result != Lbool::True { return None; } let solver = &self.solver; let constraints = self.equality_constraint_vars .iter() .filter_map(|(&c, &v)| if solver.is_true(v) { Some(c) } else { None }) .collect(); let sources = self.source_permutation_vars .iter() .filter_map(|(s, &v)| if solver.is_true(v) { Some(s.clone()) } else { None }) .collect::<Vec<_>>(); println!("sources = {:?}", sources); for (sources, v) in self.source_permutation_vars.into_iter() { if self.solver.is_true(v) { return Some((sources.to_owned(), constraints)); } } return None; } } fn source_constant_vector<T>(required: Vec<Constant>, forbidden: HashSet<Vec<Constant>>, program: &Program<T>, facts: &FactTable<T>, max_sources: usize) -> Option<(Vec<Source>, Vec<EqualityConstraint>)> where T: TruthValue { let mut state = SynthesisState::new(); state.require_constant_vector(&required, &forbidden, program, facts, max_sources, max_sources); return state.solve(); } fn create_clause<T>(program: &Program<T>, output_predicate: Predicate, output_num_terms: usize, sources: &[Source], equality_constraints: &[EqualityConstraint]) -> Clause where T: TruthValue { let num_output_vars = output_num_terms; let mut head = Literal::new_from_vec(output_predicate, (0..num_output_vars).map(|t| Term::Variable(t)).collect()); let mut back_refs = HashMap::new(); for EqualityConstraint(first, second) in equality_constraints.iter().cloned() { back_refs.insert(second, first); } println!("back_refs = {:?}", back_refs); let mut num_variables_so_far = sources.len(); let mut body: Vec<Literal> = Vec::new(); for (source_idx, source) in sources.iter().cloned().enumerate() { let terms = Vec::with_capacity(program.get_num_terms(source.predicate)); body.push(Literal::new_from_vec(source.predicate, terms)); for term_idx in 0..program.get_num_terms(source.predicate) { if term_idx == source.term_idx { if let Some(back_ref) = back_refs.get(&SourceTerm { source_idx, term_idx, }) { let referred_to = body[back_ref.source_idx].terms[back_ref.term_idx]; head.terms[source_idx] = referred_to; } else { body.last_mut() .unwrap() .terms .push(Term::Variable(source_idx)); } } else if let Some(back_ref) = back_refs.get(&SourceTerm { source_idx, term_idx, }) { let referred_to = body[back_ref.source_idx].terms[back_ref.term_idx]; body.last_mut().unwrap().terms.push(referred_to); } else { body.last_mut() .unwrap() .terms .push(Term::Variable(num_variables_so_far)); num_variables_so_far += 1; } } } Clause::new_from_vec(head, body) } fn synthesize_clause<T>(program: &mut Program<T>, output_predicate: usize, output_num_terms: usize, output_num_sources: usize, io_pairs: &[(FactTable<T>, (Vec<Constant>, Vec<Vec<Constant>>))]) -> Clause where T: TruthValue { let mut state = SynthesisState::new(); for &(ref input, ref output) in io_pairs { let required = &output.0; let forbidden = output.1.iter().cloned().collect(); state.require_constant_vector(required, &forbidden, program, input, output_num_sources, output_num_sources); } let (sources, constraints) = state.solve().unwrap(); println!("sources = {:?}", sources); println!("constraints = {:?}", constraints); let result_clause = create_clause(program, output_predicate, output_num_terms, &sources, &constraints); program.push_clause_simple(result_clause.clone()); return result_clause; } #[cfg(test)] mod tests { use super::*; use bottom_up::evaluate_bottom_up; use parser::{datalog, facts_and_program, program_lit}; fn check_source_tuples(mut iter: SourceVecIter<()>, source_tuples: &[Vec<(Predicate, usize)>]) { for tuples in source_tuples { assert_eq!(*iter.next().unwrap(), tuples .iter() .map(|&(predicate, term_idx)| { Source { predicate, term_idx, } }) .collect::<Vec<Source>>()); } assert_eq!(iter.next(), None); } #[test] fn source_iter_only_one_choice() { let prg = program_lit(r" a(0). "); let source_tuples = [vec![(0, 0)]]; check_source_tuples(SourceVecIter::new(1, 1, &prg), &source_tuples); } #[test] fn source_iter_two_terms() { let prg = program_lit(r" a(0, 0). "); let source_tuples = [vec![(0, 0)], vec![(0, 1)]]; check_source_tuples(SourceVecIter::new(1, 1, &prg), &source_tuples); } #[test] fn source_iter_two_predicates() { let prg = program_lit(r" a(0). b(0). "); let source_tuples = [vec![(0, 0)], vec![(1, 0)]]; check_source_tuples(SourceVecIter::new(1, 1, &prg), &source_tuples); } #[test] fn source_iter_two_predicates_two_terms() { let prg = program_lit(r" a(0, 0). b(0, 0). "); let source_tuples = [vec![(0, 0)], vec![(0, 1)], vec![(1, 0)], vec![(1, 1)]]; check_source_tuples(SourceVecIter::new(1, 1, &prg), &source_tuples); } #[test] fn source_iter_two_sources() { let prg = program_lit(r" a(0, 0). b(0, 0). "); let source_tuples = [vec![(0, 0)], vec![(0, 1)], vec![(1, 0)], vec![(1, 1)], vec![(0, 0), (0, 0)], vec![(0, 0), (0, 1)], vec![(0, 0), (1, 0)], vec![(0, 0), (1, 1)], vec![(0, 1), (0, 0)], vec![(0, 1), (0, 1)], vec![(0, 1), (1, 0)], vec![(0, 1), (1, 1)], vec![(1, 0), (0, 0)], vec![(1, 0), (0, 1)], vec![(1, 0), (1, 0)], vec![(1, 0), (1, 1)], vec![(1, 1), (0, 0)], vec![(1, 1), (0, 1)], vec![(1, 1), (1, 0)], vec![(1, 1), (1, 1)]]; check_source_tuples(SourceVecIter::new(1, 2, &prg), &source_tuples); } #[test] fn source_iter_three_sources() { let prg = program_lit(r" a(0, 0, 0). b(0, 0). c(0). "); let source_tuples = [vec![(0, 0)], vec![(0, 1)], vec![(0, 2)], vec![(1, 0)], vec![(1, 1)], vec![(2, 0)], vec![(0, 0), (0, 0)], vec![(0, 0), (0, 1)], vec![(0, 0), (0, 2)], vec![(0, 0), (1, 0)], vec![(0, 0), (1, 1)], vec![(0, 0), (2, 0)], vec![(0, 1), (0, 0)], vec![(0, 1), (0, 1)], vec![(0, 1), (0, 2)], vec![(0, 1), (1, 0)], vec![(0, 1), (1, 1)], vec![(0, 1), (2, 0)], vec![(0, 2), (0, 0)], vec![(0, 2), (0, 1)], vec![(0, 2), (0, 2)], vec![(0, 2), (1, 0)], vec![(0, 2), (1, 1)], vec![(0, 2), (2, 0)], vec![(1, 0), (0, 0)], vec![(1, 0), (0, 1)], vec![(1, 0), (0, 2)], vec![(1, 0), (1, 0)], vec![(1, 0), (1, 1)], vec![(1, 0), (2, 0)], vec![(1, 1), (0, 0)], vec![(1, 1), (0, 1)], vec![(1, 1), (0, 2)], vec![(1, 1), (1, 0)], vec![(1, 1), (1, 1)], vec![(1, 1), (2, 0)], vec![(2, 0), (0, 0)], vec![(2, 0), (0, 1)], vec![(2, 0), (0, 2)], vec![(2, 0), (1, 0)], vec![(2, 0), (1, 1)], vec![(2, 0), (2, 0)]]; check_source_tuples(SourceVecIter::new(1, 2, &prg), &source_tuples); } #[test] fn constant_vec_iter_simple() { let (facts, prg) = facts_and_program(r" a(0). a(1). b(0, 0). b(0, 1). "); let mut iter = ConstantVecIter::new(1, 1, &prg, &facts); // Unfortunately, the order of facts is non-deterministic, since FactTable iteration is // dependent on HashMap ordering. let expected_fact_vec_tuples = vec![(0, 0, vec![vec![0], vec![1]]), (0, 0, vec![vec![0], vec![1]]), (1, 0, vec![vec![0, 0], vec![0, 1]]), (1, 0, vec![vec![0, 0], vec![0, 1]]), (1, 1, vec![vec![0, 0], vec![0, 1]]), (1, 1, vec![vec![0, 0], vec![0, 1]])]; for ((predicate, term_idx, term_choices), (sources, facts)) in expected_fact_vec_tuples.into_iter().zip(&mut iter) { assert_eq!(vec![Source { predicate, term_idx, }], *sources); let fact_choices: HashSet<Fact> = term_choices .into_iter() .map(|terms| Fact { predicate, terms }) .collect(); assert!(fact_choices.contains(&facts[0])); } assert_eq!(iter.next(), None); } #[test] fn explain_copy() { let (facts, prg) = facts_and_program(r" a(0). "); let required = vec![0]; let forbidden = HashSet::new(); let (sources, constraints) = source_constant_vector(required, forbidden, &prg, &facts, 1) .unwrap(); assert_eq!(sources, &[Source { predicate: 0, term_idx: 0, }]); assert_eq!(constraints, &[]); } #[test] fn choose_correct_predicate() { let (facts, prg) = facts_and_program(r" a(0). b(1). c(2). d(3). "); let required = vec![2]; let forbidden = HashSet::new(); let (sources, constraints) = source_constant_vector(required, forbidden, &prg, &facts, 1) .unwrap(); assert_eq!(sources, &[Source { predicate: 2, term_idx: 0, }]); assert_eq!(constraints, &[]); } #[test] fn require_equality_constraint() { let (facts, prg) = facts_and_program(r" a(0). b(0). a(1). b(2). "); let required = vec![0]; let forbidden = [vec![1], vec![2]].iter().cloned().collect(); let (sources, constraints) = source_constant_vector(required, forbidden, &prg, &facts, 2) .unwrap(); assert_eq!(sources, &[Source { predicate: 0, term_idx: 0, }, Source { predicate: 1, term_idx: 0, }]); assert_eq!(constraints, &[EqualityConstraint(SourceTerm { source_idx: 0, term_idx: 0, }, SourceTerm { source_idx: 1, term_idx: 0, })]); } #[test] fn synth_clause_with_equality_constraint() { let (facts, mut prg) = facts_and_program(r" a(0). b(0). a(1). b(2). "); let required = vec![0]; let forbidden = [vec![1], vec![2]].iter().cloned().collect(); let (sources, constraints) = source_constant_vector(required, forbidden, &prg, &facts, 2) .unwrap(); let result_clause = create_clause(&prg, 2, 1, &sources, &constraints); println!("clause = {:?}", result_clause); prg.push_clause_simple(result_clause.clone()); println!("{}", prg); // The order of the predicates is determined by the SAT solver randomized starting // conditions. let expected_clauses = [Clause::new_from_vec(Literal::new_from_vec(2, vec![Term::Variable(0)]), vec![Literal::new_from_vec(0, vec![Term::Variable(0)]), Literal::new_from_vec(1, vec![Term::Variable(0)])]), Clause::new_from_vec(Literal::new_from_vec(2, vec![Term::Variable(0)]), vec![Literal::new_from_vec(1, vec![Term::Variable(0)]), Literal::new_from_vec(0, vec![Term::Variable(0)])])]; assert!(expected_clauses.contains(&result_clause)); } #[test] fn synth_piece_down() { let (input_0, mut prg) = facts_and_program(r" player(0). move(1). board(0, 2). board(1, 2). "); let output_0 = (vec![1, 0], vec![vec![1, 2], vec![1, 1]]); let (input_1, _) = datalog(r" player(1). move(1). board(0, 2). board(1, 2). ", &mut prg) .unwrap(); let output_1 = (vec![1, 1], vec![vec![1, 0], vec![1, 2]]); let (input_2, _) = datalog(r" player(1). move(0). board(0, 2). board(1, 2). ", &mut prg) .unwrap(); let output_2 = (vec![0, 1], vec![vec![0, 0], vec![0, 2]]); let (input_3, _) = datalog(r" player(0). move(0). board(0, 2). board(1, 2). ", &mut prg) .unwrap(); let output_3 = (vec![0, 0], vec![vec![0, 1], vec![0, 2]]); let result_clause = synthesize_clause(&mut prg, 3, 2, 2, &[(input_0, output_0), (input_1, output_1), (input_2, output_2), (input_3, output_3)]); let expected_clause = Clause::new_from_vec(Literal::new_from_vec(3, vec![Term::Variable(0), Term::Variable(1)]), vec![Literal::new_from_vec(1, vec![Term::Variable(0)]), Literal::new_from_vec(0, vec![Term::Variable(1)])]); println!("clause = {:?}", result_clause); println!("correct clause = {:?}", expected_clause); println!("{}", prg); assert_eq!(result_clause, expected_clause); } #[test] fn synth_mini_ttt_no_rule_breaking() { let (input_0, mut prg) = facts_and_program(r" player(0). move(1, 1). board(0, 0, 2). board(0, 1, 2). board(1, 0, 2). board(1, 1, 2). blank(2). "); let output_0 = (vec![1, 1, 0], vec![vec![1, 1, 1], vec![1, 1, 2]]); let (input_1, _) = datalog(r" player(1). move(0, 1). board(0, 0, 2). board(0, 1, 2). board(1, 0, 2). board(1, 1, 2). blank(2). ", &mut prg) .unwrap(); let output_1 = (vec![0, 1, 1], vec![vec![0, 1, 0], vec![0, 1, 2]]); let (input_2, _) = datalog(r" player(1). move(0, 0). board(0, 0, 2). board(0, 1, 2). board(1, 0, 2). board(1, 1, 2). blank(2). ", &mut prg) .unwrap(); let output_2 = (vec![0, 0, 1], vec![vec![0, 0, 0], vec![0, 1, 2]]); let (input_3, _) = datalog(r" player(0). move(0, 1). board(0, 0, 2). board(0, 1, 2). board(1, 0, 2). board(1, 1, 2). blank(2). ", &mut prg) .unwrap(); let output_3 = (vec![0, 1, 0], vec![vec![0, 1, 1], vec![0, 1, 2]]); let result_clause = synthesize_clause(&mut prg, 4, 3, 3, &[(input_0, output_0), (input_1, output_1), (input_2, output_2), (input_3, output_3)]); let expected_clause = Clause::new_from_vec(Literal::new_from_vec(4, vec![Term::Variable(0), Term::Variable(1), Term::Variable(2)]), vec![Literal::new_from_vec(1, vec![Term::Variable(0), Term::Variable(3)]), Literal::new_from_vec(1, vec![Term::Variable(4), Term::Variable(1)]), Literal::new_from_vec(0, vec![Term::Variable(2)])]); println!("clause = {:?}", result_clause); println!("correct clause = {:?}", expected_clause); println!("{}", prg); assert_eq!(result_clause, expected_clause); } }
solve
main.rs
fn main() { let mut s = String::from("Hello"); let r1 = &s; let r2 = &s; println!("{} and {}", r1, r2); let r3 = &mut s; println!("{}", r3); // just one mut reference or mutilply non-mut reference // non-mut reference cannot Involved in the mut reference scope // cannot borrow `s` as mutable because it is also borrowed as immutable // println!("{} and {} and {}",r1, r2, r3); println!("Hello, world!"); let my_string = String::from("hello world"); let word = first_word(&my_string[..]); println!("{}", word); let my_string_literal = "hello world"; let word = first_word(&my_string_literal[..]); println!("{}", word); // string literals is silce non-mut reference let word = first_word(my_string_literal); println!("{}", word); } fn
(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] // return &s[..]; }
first_word
referenceDataSet.go
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package latest import ( "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v2/go/pulumi" ) // A reference data set provides metadata about the events in an environment. Metadata in the reference data set will be joined with events as they are read from event sources. The metadata that makes up the reference data set is uploaded or modified through the Time Series Insights data plane APIs. type ReferenceDataSet struct { pulumi.CustomResourceState // The time the resource was created. CreationTime pulumi.StringOutput `pulumi:"creationTime"` // The reference data set key comparison behavior can be set using this property. By default, the value is 'Ordinal' - which means case sensitive key comparison will be performed while joining reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison will be used. DataStringComparisonBehavior pulumi.StringPtrOutput `pulumi:"dataStringComparisonBehavior"` // The list of key properties for the reference data set. KeyProperties ReferenceDataSetKeyPropertyResponseArrayOutput `pulumi:"keyProperties"` // Resource location Location pulumi.StringOutput `pulumi:"location"` // Resource name Name pulumi.StringOutput `pulumi:"name"` // Provisioning state of the resource. ProvisioningState pulumi.StringOutput `pulumi:"provisioningState"` // Resource tags Tags pulumi.StringMapOutput `pulumi:"tags"` // Resource type Type pulumi.StringOutput `pulumi:"type"` } // NewReferenceDataSet registers a new resource with the given unique name, arguments, and options. func NewReferenceDataSet(ctx *pulumi.Context, name string, args *ReferenceDataSetArgs, opts ...pulumi.ResourceOption) (*ReferenceDataSet, error) { if args == nil || args.EnvironmentName == nil { return nil, errors.New("missing required argument 'EnvironmentName'") } if args == nil || args.KeyProperties == nil { return nil, errors.New("missing required argument 'KeyProperties'") } if args == nil || args.Location == nil { return nil, errors.New("missing required argument 'Location'") } if args == nil || args.ReferenceDataSetName == nil
if args == nil || args.ResourceGroupName == nil { return nil, errors.New("missing required argument 'ResourceGroupName'") } if args == nil { args = &ReferenceDataSetArgs{} } aliases := pulumi.Aliases([]pulumi.Alias{ { Type: pulumi.String("azure-nextgen:timeseriesinsights/v20170228preview:ReferenceDataSet"), }, { Type: pulumi.String("azure-nextgen:timeseriesinsights/v20171115:ReferenceDataSet"), }, { Type: pulumi.String("azure-nextgen:timeseriesinsights/v20180815preview:ReferenceDataSet"), }, { Type: pulumi.String("azure-nextgen:timeseriesinsights/v20200515:ReferenceDataSet"), }, }) opts = append(opts, aliases) var resource ReferenceDataSet err := ctx.RegisterResource("azure-nextgen:timeseriesinsights/latest:ReferenceDataSet", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetReferenceDataSet gets an existing ReferenceDataSet resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetReferenceDataSet(ctx *pulumi.Context, name string, id pulumi.IDInput, state *ReferenceDataSetState, opts ...pulumi.ResourceOption) (*ReferenceDataSet, error) { var resource ReferenceDataSet err := ctx.ReadResource("azure-nextgen:timeseriesinsights/latest:ReferenceDataSet", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering ReferenceDataSet resources. type referenceDataSetState struct { // The time the resource was created. CreationTime *string `pulumi:"creationTime"` // The reference data set key comparison behavior can be set using this property. By default, the value is 'Ordinal' - which means case sensitive key comparison will be performed while joining reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison will be used. DataStringComparisonBehavior *string `pulumi:"dataStringComparisonBehavior"` // The list of key properties for the reference data set. KeyProperties []ReferenceDataSetKeyPropertyResponse `pulumi:"keyProperties"` // Resource location Location *string `pulumi:"location"` // Resource name Name *string `pulumi:"name"` // Provisioning state of the resource. ProvisioningState *string `pulumi:"provisioningState"` // Resource tags Tags map[string]string `pulumi:"tags"` // Resource type Type *string `pulumi:"type"` } type ReferenceDataSetState struct { // The time the resource was created. CreationTime pulumi.StringPtrInput // The reference data set key comparison behavior can be set using this property. By default, the value is 'Ordinal' - which means case sensitive key comparison will be performed while joining reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison will be used. DataStringComparisonBehavior pulumi.StringPtrInput // The list of key properties for the reference data set. KeyProperties ReferenceDataSetKeyPropertyResponseArrayInput // Resource location Location pulumi.StringPtrInput // Resource name Name pulumi.StringPtrInput // Provisioning state of the resource. ProvisioningState pulumi.StringPtrInput // Resource tags Tags pulumi.StringMapInput // Resource type Type pulumi.StringPtrInput } func (ReferenceDataSetState) ElementType() reflect.Type { return reflect.TypeOf((*referenceDataSetState)(nil)).Elem() } type referenceDataSetArgs struct { // The reference data set key comparison behavior can be set using this property. By default, the value is 'Ordinal' - which means case sensitive key comparison will be performed while joining reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison will be used. DataStringComparisonBehavior *string `pulumi:"dataStringComparisonBehavior"` // The name of the Time Series Insights environment associated with the specified resource group. EnvironmentName string `pulumi:"environmentName"` // The list of key properties for the reference data set. KeyProperties []ReferenceDataSetKeyProperty `pulumi:"keyProperties"` // The location of the resource. Location string `pulumi:"location"` // Name of the reference data set. ReferenceDataSetName string `pulumi:"referenceDataSetName"` // Name of an Azure Resource group. ResourceGroupName string `pulumi:"resourceGroupName"` // Key-value pairs of additional properties for the resource. Tags map[string]string `pulumi:"tags"` } // The set of arguments for constructing a ReferenceDataSet resource. type ReferenceDataSetArgs struct { // The reference data set key comparison behavior can be set using this property. By default, the value is 'Ordinal' - which means case sensitive key comparison will be performed while joining reference data with events or while adding new reference data. When 'OrdinalIgnoreCase' is set, case insensitive comparison will be used. DataStringComparisonBehavior pulumi.StringPtrInput // The name of the Time Series Insights environment associated with the specified resource group. EnvironmentName pulumi.StringInput // The list of key properties for the reference data set. KeyProperties ReferenceDataSetKeyPropertyArrayInput // The location of the resource. Location pulumi.StringInput // Name of the reference data set. ReferenceDataSetName pulumi.StringInput // Name of an Azure Resource group. ResourceGroupName pulumi.StringInput // Key-value pairs of additional properties for the resource. Tags pulumi.StringMapInput } func (ReferenceDataSetArgs) ElementType() reflect.Type { return reflect.TypeOf((*referenceDataSetArgs)(nil)).Elem() }
{ return nil, errors.New("missing required argument 'ReferenceDataSetName'") }
operators.py
from typing import Iterable __all__ = ['in_', 'not_in', 'exists', 'not_exists', 'equal', 'not_equal'] class Operator: def __init__(self, op_name: str, op: str, value=None): self.op = op self.value = value self.op_name = op_name def encode(self, key): return f"{key}{self.op}{self.value}"
class SequenceOperator(Operator): def encode(self, key): return f"{key} {self.op} ({','.join(self.value)})" class BinaryOperator(Operator): pass class UnaryOperator(Operator): def encode(self, key): return f"{self.op}{key}" def in_(values: Iterable) -> SequenceOperator: return SequenceOperator('in_', 'in', sorted(values)) def not_in(values: Iterable) -> SequenceOperator: return SequenceOperator('not_in', 'notin', sorted(values)) def exists() -> UnaryOperator: return UnaryOperator('exists', '') def not_exists() -> UnaryOperator: return UnaryOperator('not_exists', '!') def equal(value: str) -> BinaryOperator: return BinaryOperator('equal', '=', value) def not_equal(value: str) -> BinaryOperator: return BinaryOperator('not_equal', '!=', value)
KChart.tsx
import * as React from 'react'; import { Button, EmptyState, EmptyStateIcon, EmptyStateBody, Expandable } from '@patternfly/react-core'; import { ChartArea, ChartBar, ChartScatter, ChartLine } from '@patternfly/react-charts'; import { CubesIcon, AngleDoubleLeftIcon, ExpandArrowsAltIcon, ErrorCircleOIcon } from '@patternfly/react-icons'; import { ChartModel } from 'types/Dashboards'; import { VCLines, RawOrBucket, RichDataPoint, LineInfo } from 'types/VictoryChartInfo'; import { Overlay } from 'types/Overlay'; import ChartWithLegend from './ChartWithLegend'; import { BrushHandlers } from './Container'; type KChartProps<T extends LineInfo> = { chart: ChartModel; data: VCLines<RichDataPoint>; isMaximized: boolean; onToggleMaximized: () => void; onClick?: (datum: RawOrBucket<T>) => void; brushHandlers?: BrushHandlers; overlay?: Overlay<T>; timeWindow?: [Date, Date]; }; export const maximizeButtonStyle: React.CSSProperties = { marginBottom: '-3.5em', marginRight: '0.8em', top: '-2.7em', position: 'relative', float: 'right' }; type State = { collapsed: boolean; }; type ChartTypeData = { fill: boolean; stroke: boolean; groupOffset: number; seriesComponent: React.ReactElement; sizeRatio: number; }; const lineInfo: ChartTypeData = { fill: false, stroke: true, groupOffset: 0, seriesComponent: <ChartLine />, sizeRatio: 1.0 }; const areaInfo: ChartTypeData = { fill: true, stroke: false, groupOffset: 0, seriesComponent: <ChartArea />, sizeRatio: 1.0 }; const barInfo: ChartTypeData = { fill: true, stroke: false, groupOffset: 7, seriesComponent: <ChartBar />, sizeRatio: 1 / 6 }; const scatterInfo: ChartTypeData = { fill: true, stroke: false, groupOffset: 0, seriesComponent: <ChartScatter />, sizeRatio: 1 / 30 }; class KChart<T extends LineInfo> extends React.Component<KChartProps<T>, State> { constructor(props: KChartProps<T>) { super(props); this.state = { collapsed: this.props.chart.startCollapsed || (!this.props.chart.error && this.isEmpty()) }; } componentDidUpdate(prevProps: KChartProps<T>) { // Check when there is a change on empty datapoints on a refresh to draw the chart collapsed the first time // User can change the state after that point const propsIsEmpty = !this.props.data.some(s => s.datapoints.length !== 0); const prevPropsIsEmpty = !prevProps.data.some(s => s.datapoints.length !== 0); if (propsIsEmpty !== prevPropsIsEmpty) { this.setState({ collapsed: propsIsEmpty }); } } render() { return ( <Expandable toggleText={this.props.chart.name} onToggle={() => { this.setState({ collapsed: !this.state.collapsed }); }} isExpanded={!this.state.collapsed} > {this.props.chart.error ? this.renderError() : this.isEmpty() ? this.renderEmpty() : this.renderChart()} </Expandable> ); } private determineChartType() { if (this.props.chart.chartType === undefined) { return this.props.chart.xAxis === 'series' ? barInfo : lineInfo; } const chartType = this.props.chart.chartType; switch (chartType) { case 'area': return areaInfo; case 'bar': return barInfo; case 'scatter': return scatterInfo; case 'line': default: return lineInfo; } } private renderChart() { if (this.state.collapsed) { return undefined; } const typeData = this.determineChartType(); const minDomain = this.props.chart.min === undefined ? undefined : { y: this.props.chart.min }; const maxDomain = this.props.chart.max === undefined ? undefined : { y: this.props.chart.max }; return ( <> {this.props.onToggleMaximized && ( <div style={maximizeButtonStyle}> <Button variant="secondary" onClick={this.props.onToggleMaximized}> {this.props.isMaximized ? <AngleDoubleLeftIcon /> : <ExpandArrowsAltIcon />} </Button> </div> )} <ChartWithLegend data={this.props.data} seriesComponent={typeData.seriesComponent} fill={typeData.fill} stroke={typeData.stroke} groupOffset={typeData.groupOffset} sizeRatio={typeData.sizeRatio} overlay={this.props.overlay} unit={this.props.chart.unit}
brushHandlers={this.props.brushHandlers} timeWindow={this.props.timeWindow} xAxis={this.props.chart.xAxis} /> </> ); } private isEmpty(): boolean { return !this.props.data.some(s => s.datapoints.length !== 0); } private renderEmpty() { return ( <EmptyState variant="full"> <EmptyStateIcon icon={CubesIcon} /> <EmptyStateBody>No data available</EmptyStateBody> </EmptyState> ); } private renderError() { return ( <EmptyState variant="full"> <EmptyStateIcon icon={() => <ErrorCircleOIcon style={{ color: '#cc0000' }} width={32} height={32} />} /> <EmptyStateBody> An error occured while fetching this metric: <p> <i>{this.props.chart.error}</i> </p> </EmptyStateBody> </EmptyState> ); } } export default KChart;
moreChartProps={{ minDomain: minDomain, maxDomain: maxDomain }} onClick={this.props.onClick}
645E.go
package main import ( "bufio" "bytes" . "fmt" "io" ) // github.com/EndlessCheng/codeforces-go func CF645E(in io.Reader, out io.Writer) { const mod int = 1e9 + 7 var n, k int var s []byte Fscan(bufio.NewReader(in), &n, &k, &s) for i := range s { s[i] -= 'a' } perm := make([]byte, 0, k) vis := make([]bool, k) for i := len(s) - 1; i >= 0; i-- { b := s[i] if !vis[b] { vis[b] = true perm = append(perm, b) } } for i, b := range vis { if !b {
} for i := 0; i < k/2; i++ { perm[i], perm[k-1-i] = perm[k-1-i], perm[i] } s = append(append(s, bytes.Repeat(perm, n/k)...), perm[:n%k]...) f := [26]int{} sumF := 0 for _, b := range s { tmp := (sumF + mod - f[b]) % mod f[b] = (sumF + 1) % mod sumF = (tmp + f[b]) % mod } Fprint(out, (sumF+1)%mod) } //func main() { CF645E(os.Stdin, os.Stdout) }
perm = append(perm, byte(i)) }
helpers.go
package assets import ( "bytes" "image" "io" "io/ioutil" "log" "path/filepath" ) var ( CCIconPath string ) func init() { tempPath, err := ioutil.TempDir("", "icons") if err != nil { log.Fatalf("Failed to create temporary directory for icons: %s", err) }
} CCIconPath = filepath.Join(tempPath, "icons", "cc_icon.png") } func Reader(name string) io.Reader { return bytes.NewReader(MustAsset(name)) } func Image(name string) image.Image { icon, _, err := image.Decode(Reader(name)) if err != nil { log.Fatalf("Failed to decode image: %s", err) } return icon }
err = RestoreAsset(tempPath, "icons/cc_icon.png") if err != nil { log.Fatalf("Failed to restore CC icon: %s", err)
test_bicycle_timeseries.py
#!/usr/bin/env python3 import unittest from unittest.mock import patch, MagicMock import pandas as pd import numpy as np from tmc import points from tmc.utils import load, get_out, patch_helper module_name="src.bicycle_timeseries" bicycle_timeseries = load(module_name, "bicycle_timeseries") main = load(module_name, "main") ph = patch_helper(module_name) @points('p05-08.1') class BicycleTimeseries(unittest.TestCase): # @classmethod # def setUpClass(cls): # cls.df = bicycle_timeseries()
self.df = bicycle_timeseries() def test_shape(self): self.assertEqual(self.df.shape, (37128, 20), msg="Incorrect shape!") def test_columns(self): cols = ['Auroransilta', 'Eteläesplanadi', 'Huopalahti (asema)', 'Kaisaniemi/Eläintarhanlahti', 'Kaivokatu', 'Kulosaaren silta et.', 'Kulosaaren silta po. ', 'Kuusisaarentie', 'Käpylä, Pohjoisbaana', 'Lauttasaaren silta eteläpuoli', 'Merikannontie', 'Munkkiniemen silta eteläpuoli', 'Munkkiniemi silta pohjoispuoli', 'Heperian puisto/Ooppera', 'Pitkäsilta itäpuoli', 'Pitkäsilta länsipuoli', 'Lauttasaaren silta pohjoispuoli', 'Ratapihantie', 'Viikintie', 'Baana'] np.testing.assert_array_equal(self.df.columns, cols, err_msg="Incorrect columns!") def test_index(self): self.assertIsInstance(self.df.index[0], pd.Timestamp, msg="Expected index to have type timestamp!") self.assertEqual(self.df.index[0], pd.to_datetime("2014-1-1 00:00"), msg="Incorrect first index!") self.assertEqual(self.df.index[1], pd.to_datetime("2014-1-1 01:00"), msg="Incorrect second index!") def test_calls(self): with patch(ph("bicycle_timeseries"), wraps=bicycle_timeseries) as pbts,\ patch(ph("pd.read_csv"), wraps=pd.read_csv) as prc,\ patch(ph("pd.to_datetime"), wraps=pd.to_datetime) as pdatetime: main() pbts.assert_called_once() prc.assert_called_once() pdatetime.assert_called() if __name__ == '__main__': unittest.main()
def setUp(self):
__init__.py
""" Created by Robin Baumann <[email protected]> at 08.06.20.
"""
Scale9Button.ts
module siouxjs.ui { "use strict"; export class Sc
xtends Button { private _objStateOn: Scale9ButtonState; private _objStateDown: Scale9ButtonState; private _objStateOver: Scale9ButtonState; private _label: string; private _textAlign: string; private _width: number; private _height: number; private _bScaleTextura: boolean; private _objHitArea: createjs.Shape; public set objHitArea(value: createjs.Shape) { this._objHitArea = value; } public get objHitArea(): createjs.Shape { return this._objHitArea; } constructor(label: string, bScaleTextura: boolean = true, image9On?: Scale9Bitmap, marginOn?: createjs.Rectangle, image9Down?: Scale9Bitmap, marginDown?: createjs.Rectangle, image9Over?: Scale9Bitmap, marginOver?: createjs.Rectangle) { super(); this._bScaleTextura = bScaleTextura; // Criar Scale9Bitmap ON if (image9On == null) { var image = <HTMLImageElement> siouxjs.Assets[Theme.Button9.imagemOn]; var size: createjs.Rectangle = Theme.Button9.sizeOn; image9On = new Scale9Bitmap(new createjs.Bitmap(image).image, size, this._bScaleTextura); } if (marginOn == null) { var margin: createjs.Rectangle = Theme.Button9.marginOn; } this._objStateOn = new Scale9ButtonState(image9On, margin, Theme.Button9.fontOn, Theme.Button9.colorOn,this._bScaleTextura); // Criar Scale9Bitmap DOWN if (image9Down == null) { image = <HTMLImageElement> siouxjs.Assets[Theme.Button9.imagemDown]; size = Theme.Button9.sizeDown; image9Down = new Scale9Bitmap(new createjs.Bitmap(image).image, size, this._bScaleTextura); } if (marginDown == null) { margin = Theme.Button9.marginDown; } this._objStateDown = new Scale9ButtonState(image9Down, margin, Theme.Button9.fontDown, Theme.Button9.colorDown, this._bScaleTextura); // Imagem Over apenas para Desktop if (!util.Browser.isMobile()) { // Criar Scale9Bitmap ON if (image9Over == null) { image = <HTMLImageElement> siouxjs.Assets[Theme.Button9.imagemOver]; size = Theme.Button9.sizeOver; image9Over = new Scale9Bitmap(new createjs.Bitmap(image).image, size, this._bScaleTextura); } if (marginOver == null) { margin = Theme.Button9.marginOver; } this._objStateOver = new Scale9ButtonState(image9Over, margin, Theme.Button9.fontOver, Theme.Button9.colorOver, this._bScaleTextura); this.addChild(this._objStateOn, this._objStateDown, this._objStateOver); } else { this.addChild(this._objStateOn, this._objStateDown); } this.label = label; this.state(); this.updateHitArea(); } public get label(): string { return this._label; } public set label(value: string) { this._label = value; this._objStateOn.label = this._label; this._objStateDown.label = this._label; if (!util.Browser.isMobile()) { this._objStateOver.label = this._label; } this.updateHitArea(); } public get width(): number { return this._width; } public set width(value: number) { this._width = value; this._objStateOn.width = this._width; this._objStateDown.width = this._width; if (this._objStateOver != null) { this._objStateOver.width = this._width; } this.updateHitArea(); } public get height(): number { return this._height; } public set height(value: number) { this._height = value; this._objStateOn.height = this._height; this._objStateDown.height = this._height; if (this._objStateOver != null) { this._objStateOver.height = this._height; } this.updateHitArea(); } public set textAlign(value: string) { this._textAlign = value; this._objStateOn.textAlign = this._textAlign; this._objStateDown.textAlign = this._textAlign; if (this._objStateOver != null) { this._objStateOver.textAlign = this._textAlign; } this.updateHitArea(); } public setIcone(value: SXBitmap, x: number, y: number) { this._objStateOn.setIcone (value.clone(),x,y); this._objStateDown.setIcone(value.clone(), x, y); if (this._objStateOver != null) { this._objStateOver.setIcone(value.clone(), x, y); } this.updateHitArea(); } public get objStateOn(): Scale9ButtonState { return this._objStateOn; } public get objStateDown(): Scale9ButtonState { return this._objStateDown; } public get objStateOver(): Scale9ButtonState { return this._objStateOver; } public state(): void { this._objStateOn.visible = false; this._objStateDown.visible = false; if (this._objStateOver != null) { this._objStateOver.visible = false; } switch (this.nState) { case 1: // Down this._objStateDown.visible = true; break; case 2: // Over if (this._objStateOver != null) { this._objStateOver.visible = true; } break; default: // Normal this._objStateOn.visible = true; } } private updateHitArea(): void { // HitArea - for better performance this._objHitArea = new createjs.Shape(); this._objHitArea.graphics.beginFill("#000").drawRect(0, 0, this._objStateOn.getBounds().width, this._objStateOn.getBounds().height); this.hitArea = this._objHitArea; } } }
ale9Button e
CSRExample.tsx
import { useEffect } from 'react' import { Grid, makeStyles, Theme, createStyles, Typography, Paper, Box, Hidden, Button, SwipeableDrawer, Link, } from '@material-ui/core' import { Alert } from '@material-ui/lab' import ArrowBackIcon from '@material-ui/icons/ArrowBack' import ListIcon from '@material-ui/icons/List' import NextLink from 'next/link' import React from 'react' import { useRouter } from 'next/router' import { currentManualNameState, currentPageTitleState, mobileMenuOpenState, } from '../state/atoms' import { useRecoilState, useSetRecoilState } from 'recoil' import { ReactQueryDevtools } from 'react-query-devtools' import { ReactQueryStatusLabel } from '../components/ReactQueryStatusLabel' import ManualDisplay from '../components/ManualDisplay' import ManualsList from '../components/ManualsList' const useStyles = makeStyles((theme: Theme) => createStyles({ root: { display: 'flex', flexDirection: 'column', }, flexGrow: { flexGrow: 1, }, menuButton: { marginRight: theme.spacing(2), [theme.breakpoints.up('sm')]: { display: 'none', }, }, ManualsListPaper: { width: '100%', minWidth: '250px', height: '100%', padding: theme.spacing(3), overflowY: 'auto', }, MainManual: { padding: theme.spacing(3), width: '100%', height: '100%', }, MobileManualsMenuContainer: { marginTop: -theme.spacing(3), }, MobileManualsMenu: { padding: theme.spacing(3), width: '100%', }, MobileSideBar: { padding: theme.spacing(3), }, imageBanner: { display: 'flex', flexDirection: 'row', width: '100%', alignItems: 'center', justifyContent: 'center', '& > img': { minWidth: '150px', maxWidth: '400px', width: '30%', }, }, }), ) export const CSRExample: React.FunctionComponent = () => { const classes = useStyles() const router = useRouter() const [currentManualName, setCurrentManualName] = useRecoilState( currentManualNameState, ) const [mobileMenuOpen, setMobileMenuOpen] = useRecoilState( mobileMenuOpenState, ) const setCurrentPageTitle = useSetRecoilState(currentPageTitleState) // On load or when the Query string changes make sure we set our states. useEffect(() => { if (router.query && router.query.manual) { const manualString: string = router.query.manual as string setCurrentManualName(manualString) } else { setCurrentManualName('') } }, [router]) const toggleDrawer = (open: boolean) => ( event: React.KeyboardEvent | React.MouseEvent, ) => { if ( event && event.type === 'keydown' && ((event as React.KeyboardEvent).key === 'Tab' || (event as React.KeyboardEvent).key === 'Shift') ) { return } setMobileMenuOpen(open) } const BackButton = () => ( <NextLink href="/" passHref> <Button variant="outlined" color="default" startIcon={<ArrowBackIcon />} size="medium" style={{ marginBottom: '20px' }} > Back to index </Button> </NextLink> ) const SelectManualsButton = () => ( <Button variant="contained" color="primary" size="medium" onClick={toggleDrawer(true)} startIcon={<ListIcon />} style={{ marginBottom: '20px' }} > Select Manual </Button> ) const MainContent = () => { if (currentManualName.length == 0) { setCurrentPageTitle(`CSR Example`) return <CSRExampleText /> } else { return <ManualDisplay /> } } const CSRExampleText = () => ( <Box> <Typography variant="h4" gutterBottom> Server Rendered Frame, Client Rendered Content </Typography> <Box className={classes.imageBanner}> <img src="/images/undraw_next_js_8g5m.png" /> <Typography variant="h2" color="primary"> & </Typography> <img src="/images/undraw_react_y7wq.png" /> </Box> <Typography variant="body1" paragraph> This page is an example of a pre rendered static frame (Thanks{' '} <Link href="https://nextjs.org/">Next.js!</Link> 👍⚡) but then Client Side Rendered content (Cheers{' '} <Link href="https://reactjs.org/">React</Link> and Azure Functions! 🍻🍻). This is ideal when you need to be able to display up to the second dynamic content from the server, based on user input. The other use of this interaction with Azure Functions is if you need to do something server side such as send an email or edit persistent data in something like a database. </Typography> <Typography variant="body1" paragraph> In this example we are also showing the handling of State. We&apos;ve decided to split this into two types, Client state (Global) and Sever State (Data). To highlight how this is being handled you will see some little data tags to show some of the nifty features of our server state handler,{' '} <Link href="https://react-query.tanstack.com/docs/videos"> React-Query </Link> , such as caching results then refreshing them when needed, refreshing data when refocusing on the browser tab after having been away for a while (😴😴) and automatic query retrying. For client state we are using recoil that is also pretty damn neat (Find out all about{' '} <Link href="https://recoiljs.org/"> recoil and it&apos;s Atoms here! </Link>{' '} ⚛⚛). With these two together we can avoid the need for something more boilerplate intensive such as{' '} <Link href="https://redux.js.org/">redux</Link> and{' '} <Link href="https://github.com/reduxjs/redux-thunk">thunk</Link> </Typography> <Alert severity="warning" style={{ marginBottom: '20px' }}> Note that we have purposely slowed down the Azure Function API&apos;s for this example with a 2 second sleep. AF&apos;s are normally lightening quick! ⚡⚡ </Alert> <Typography variant="body1" paragraph> We&apos;ve also included a notification handler in the form of{' '} <Link href="https://github.com/iamhosseindhv/notistack">NotiStack</Link>{' '} so you can, for example, notify users on the completion of those async tasks you have been firing off to azure functions! In this case we&apos;ve just shoe horned it into the example when you clear the selection but it gives you the idea! </Typography> <Typography variant="body1" paragraph> To see all this in action select a Person Manual from the menu. ↖↖ </Typography> </Box> ) // Return the whole page setup. return ( <Grid container direction="column" className={classes.root} style={{ padding: '12px' }} > <Hidden lgUp> <Grid item container className={classes.MobileManualsMenuContainer}> <Paper className={classes.MobileManualsMenu}> <Box display="flex" flexDirection="row" justifyContent="flex-start"> <BackButton /> </Box> <SwipeableDrawer anchor="left" open={mobileMenuOpen} onClose={toggleDrawer(false)} onOpen={toggleDrawer(true)} > <Box className={classes.MobileSideBar}> <ManualsList /> <ReactQueryStatusLabel style={{ alignSelf: 'flex-end', width: 'fit-content', maxWidth: '230px', marginTop: '20px', }} queryKey={['manuals']} /> </Box> </SwipeableDrawer> </Paper> </Grid> </Hidden> <Grid item container direction="row" className={classes.flexGrow} spacing={1} > <Hidden mdDown> <Grid md={false} lg={2} item> <Paper className={classes.ManualsListPaper} elevation={5}> <ManualsList /> <ReactQueryStatusLabel style={{ alignSelf: 'flex-end', width: 'fit-content', maxWidth: '230px', marginTop: '20px', }} queryKey={['manuals']} />
</Grid> </Hidden> <Grid md={12} lg={8} item container direction="row" className={classes.flexGrow} > <Paper elevation={5} className={classes.MainManual}> <Hidden lgUp> <SelectManualsButton /> </Hidden> <Hidden mdDown> <BackButton /> </Hidden> <Box height="100%" width="100%" display="flex" alignItems="flex-start" > <MainContent /> </Box> </Paper> </Grid> <Grid md={false} lg={2} item className="Gutter"></Grid> </Grid> <ReactQueryDevtools /> </Grid> ) } // // This is a bit of example code used to test if the NEXT_PUBLIC_API // // environment variable can be seen both on server and client side. // export async function getStaticProps() { // // Do our server side code // console.log("API address Server:") // console.log(process.env.NEXT_PUBLIC_API); // // // Continue the page load! // return {props:{}} // }; export default CSRExample
</Paper>
run_decoding_WM_across_epochs_and_conditions.py
"""Run decoding analyses in sensors space accross memory content and visual perception for the working memory task and save decoding performance""" # Authors: Romain Quentin <[email protected]> # Jean-Remi King <[email protected]> # # License: BSD (3-clause) import os import os.path as op import numpy as np import mne from h5io import read_hdf5 from mne.decoding import GeneralizingEstimator, LinearModel from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import Ridge from sklearn.metrics import make_scorer from sklearn.model_selection import StratifiedKFold from jr.gat import (AngularRegression, scorer_spearman, scorer_angle) from base import (complete_behavior, get_events_interactions) from config import path_data import sys subject = sys.argv[1] # read a swarm file for parralel computing on biowulf output_folder = '/sensors_accross_epochs_and_conditions/' # Create result folder results_folder = op.join(path_data + 'results/' + subject + output_folder) if not os.path.exists(results_folder): os.makedirs(results_folder) # read behavior fname = op.join(path_data, subject, 'behavior_Target.hdf5') events = read_hdf5(fname) events = complete_behavior(events) events = get_events_interactions(events) # read stimulus epochs fname = op.join(path_data, subject, 'epochs_Target.fif') epochs_target = mne.read_epochs(fname) epochs_target.pick_types(meg=True, ref_meg=False) epochs_target.crop(-0.2, 0.9) # read cue epochs fname = op.join(path_data, subject, 'epochs_Cue.fif') epochs_cue = mne.read_epochs(fname) epochs_cue.pick_types(meg=True, ref_meg=False) epochs_cue.crop(0, 1.5) # read probe epochs fname = op.join(path_data, subject, 'epochs_Probe.fif') epochs_probe = mne.read_epochs(fname) epochs_probe.pick_types(meg=True, ref_meg=False) epochs_probe.crop(0, 0.9) # Concatenate the data of the three epochs X0 = epochs_target._data X1 = epochs_cue._data X2 = epochs_probe._data
# Define pair of analyses (train on the 2nd and test on the 1st ) paired_analyses = [['target_sfreq_cue_left_sfreq', 'left_sfreq'], ['target_sfreq_cue_right_sfreq', 'right_sfreq'], ['left_sfreq', 'target_sfreq_cue_left_sfreq'], ['right_sfreq', 'target_sfreq_cue_right_sfreq'], ['target_angle_cue_left_angle', 'left_angle'], ['target_angle_cue_right_angle', 'right_angle'], ['left_angle', 'target_angle_cue_left_angle'], ['right_angle', 'target_angle_cue_right_angle']] # Loop across each pair of analyses for paired_analysis in paired_analyses: y_test = np.array(events[paired_analysis[0]]) y_train = np.array(events[paired_analysis[1]]) # Define estimators depending on the analysis if 'angle' in paired_analysis[0][:14]: clf = make_pipeline(StandardScaler(), LinearModel(AngularRegression(Ridge(), independent=False))) scorer = scorer_angle kwargs = dict() gat = GeneralizingEstimator(clf, scoring=make_scorer(scorer), n_jobs=24, **kwargs) y_test = np.array(y_test, dtype=float) y_train = np.array(y_train, dtype=float) elif 'sfreq' in paired_analysis[0][:14]: clf = make_pipeline(StandardScaler(), LinearModel(Ridge())) scorer = scorer_spearman kwargs = dict() gat = GeneralizingEstimator(clf, scoring=make_scorer(scorer), n_jobs=24, **kwargs) y_test = np.array(y_test, dtype=float) y_train = np.array(y_train, dtype=float) # only consider trials with correct fixation sel = np.where(events['is_eye_fixed'] == 1)[0] y_train = y_train[sel] y_test = y_test[sel] X = np.concatenate((X0, X1, X2), axis=2) X = X[sel] # only consider non NaN values # Run decoding accross condition cv = StratifiedKFold(7) scores = list() scs = list() if np.isnan(y_train).any(): sel = np.where(~np.isnan(y_train))[0] for train, test in cv.split(X[sel], y_train[sel]): gat.fit(X[sel][train], y_train[sel][train]) score = gat.score(X[sel][test], y_test[sel][test]) sc = gat.score(X[sel][test], y_train[sel][test]) # test on same scores.append(score) scs.append(sc) scores = np.mean(scores, axis=0) scs = np.mean(scs, axis=0) else: for train, test in cv.split(X, y_train): y_te = y_test[test] X_te = X[test] y_te = y_te[np.where(~np.isnan(y_te))[0]] X_te = X_te[np.where(~np.isnan(y_te))[0]] y_tr = y_train[train] X_tr = X[train] y_tr = y_tr[np.where(~np.isnan(y_tr))[0]] X_tr = X_tr[np.where(~np.isnan(y_tr))[0]] y_tr_te = y_train[test] X_tr_te = X[test] y_tr_te = y_tr_te[np.where(~np.isnan(y_tr_te))[0]] X_tr_te = X_tr_te[np.where(~np.isnan(y_tr_te))[0]] gat.fit(X_tr, y_tr) score = gat.score(X_te, y_te) sc = gat.score(X_tr_te, y_tr_te) # test on same scores.append(score) scs.append(sc) scores = np.mean(scores, axis=0) scs = np.mean(scs, axis=0) # save cross-validated scores fname = results_folder +\ '%s_scores_%s_cross_%s.npy' % (subject, paired_analysis[0], paired_analysis[1]) np.save(fname, np.array(scores)) # save accross condition scores fname = results_folder +\ '%s_scores_%s.npy' % (subject, paired_analysis[1]) np.save(fname, np.array(scs)) # save scores test/train on same condition
X = np.concatenate((X0, X1, X2), axis=2)
graph-pattern.spec.js
let chai = require('chai'); chai.should(); import GraphPattern from '../../src/sparql/graph-pattern'; import Triple from '../../src/sparql/triple'; import Filter from '../../src/sparql/filter'; import Query from '../../src/sparql/query'; describe('GraphPattern', () => { let triple = new Triple('?x foaf:mbox ?mbox'), filter = new Filter('langMatches( lang(?label), "de" )'), pattern; it('creates pattern from array', () => { pattern = new GraphPattern([triple, filter]); pattern.toString().should.equal('{ ?x foaf:mbox ?mbox . FILTER (langMatches( lang(?label), "de" )) }'); }); it('returns element count', () => {
pattern.clear(); pattern.countElements().should.equal(0); }); it('creates pattern from single value', () => { pattern = new GraphPattern(triple); pattern.toString().should.equal('{ ?x foaf:mbox ?mbox }'); }); it('adds element at end', () => { pattern.addElement(filter); pattern.toString().should.equal('{ ?x foaf:mbox ?mbox . FILTER (langMatches( lang(?label), "de" )) }'); }); it('inserts element at index 0', () => { pattern.addElement(triple, 0); pattern.toString().should.equal('{ ?x foaf:mbox ?mbox . ?x foaf:mbox ?mbox . FILTER (langMatches( lang(?label), "de" )) }'); }); it('removes 2 elements at index 1', () => { pattern.removeElements(1, 2); pattern.toString().should.equal('{ ?x foaf:mbox ?mbox }'); }); it('removes 1 element at beginning', () => { pattern.removeElements(); pattern.countElements().should.equal(0); }); it('adds graph pattern with subquery', () => { let query = new Query(null) .select('*') .where(new GraphPattern(triple)); pattern.addElement(triple); pattern.addElement(query); pattern.addElement(filter); pattern.toString().should.equal('{ ?x foaf:mbox ?mbox . { SELECT * WHERE { ?x foaf:mbox ?mbox } } FILTER (langMatches( lang(?label), "de" )) }'); }); });
pattern.countElements().should.equal(2); }); it('clears elements', () => {
build.rs
use prelude::*; use rayon::prelude::*; pub fn cli() -> App { subcommand("build") .about("Build infrastructure") .arg(Arg::with_name("SERVICE").help("The name of the service to build")) .arg(project()) } pub fn exec(args: &ArgMatches) -> CliResult { let mut project = args.project()?; if let Some(name) = args.value_of("SERVICE") { let mut service = project.find_service(name)?; let _ = service.clone_repo(); service.build() } else { let _ = create_network(&project); let _ = create_volumes(&project); let _ = pull_latest_images(); let _ = build_images(); let _ = clone_services(&mut project); let _ = build_services(&mut project); Ok(()) } } fn create_network(project: &Project) -> CliResult { println!("\nCreating '{}' network", &project.name); let _ = docker() .stdout(Stdio::null()) .stderr(Stdio::null()) .args(&["network", "create", &project.name]) .spawn()? .wait(); Ok(()) } fn create_volumes(project: &Project) -> CliResult { println!("\nCreating volumes"); project .volumes .par_iter() .map(|s| create_volume(s.as_str())) .collect::<Vec<CliResult>>(); Ok(()) } fn create_volume(name: &str) -> CliResult { println!("Creating volume: {}", name); let _ = docker() .stdout(Stdio::null()) .args(&["volume", "create", "--name", name]) .spawn()? .wait(); Ok(()) } fn pull_latest_images() -> CliResult { println!("\nPulling latest images..."); let _ = docker_compose().args(&["pull"]).spawn()?.wait();
println!("\nBuilding images..."); let _ = docker_compose().args(&["build"]).spawn()?.wait(); Ok(()) } fn clone_services(project: &mut Project) -> CliResult { project .services .par_iter_mut() .map(|ref mut service| service.clone_repo()) .collect::<Vec<CliResult>>(); Ok(()) } fn build_services(project: &mut Project) -> CliResult { project .services .par_iter_mut() .map(|ref mut service| service.build()) .collect::<Vec<CliResult>>(); Ok(()) }
Ok(()) } fn build_images() -> CliResult {
lib.rs
#![deny(clippy::integer_arithmetic)] #![deny(clippy::indexing_slicing)] pub mod alloc; pub mod allocator_bump; pub mod deprecated; pub mod serialization; pub mod syscalls; pub mod upgradeable; pub mod upgradeable_with_jit; pub mod with_jit; #[macro_use] extern crate solana_metrics; use { crate::{ serialization::{deserialize_parameters, serialize_parameters}, syscalls::SyscallError, }, log::{log_enabled, trace, Level::Trace}, solana_measure::measure::Measure, solana_program_runtime::{ ic_logger_msg, ic_msg, invoke_context::{ComputeMeter, Executor, InvokeContext}, log_collector::LogCollector, stable_log, sysvar_cache::get_sysvar_with_account_check, }, solana_rbpf::{ aligned_memory::AlignedMemory, ebpf::HOST_ALIGN, elf::Executable, error::{EbpfError, UserDefinedError}, static_analysis::Analysis, verifier::{self, VerifierError}, vm::{Config, EbpfVm, InstructionMeter}, }, solana_sdk::{ account::{ReadableAccount, WritableAccount}, account_utils::State, bpf_loader, bpf_loader_deprecated, bpf_loader_upgradeable::{self, UpgradeableLoaderState}, entrypoint::{HEAP_LENGTH, SUCCESS}, feature_set::{ cap_accounts_data_len, disable_bpf_deprecated_load_instructions, disable_bpf_unresolved_symbols_at_runtime, disable_deprecated_loader, do_support_realloc, reduce_required_deploy_balance, requestable_heap_size, }, instruction::{AccountMeta, InstructionError}, keyed_account::{keyed_account_at_index, KeyedAccount}, loader_instruction::LoaderInstruction, loader_upgradeable_instruction::UpgradeableLoaderInstruction, program_error::MAX_ACCOUNTS_DATA_SIZE_EXCEEDED, program_utils::limited_deserialize, pubkey::Pubkey, saturating_add_assign, system_instruction::{self, MAX_PERMITTED_DATA_LENGTH}, }, std::{cell::RefCell, fmt::Debug, pin::Pin, rc::Rc, sync::Arc}, thiserror::Error, }; solana_sdk::declare_builtin!( solana_sdk::bpf_loader::ID, solana_bpf_loader_program, solana_bpf_loader_program::process_instruction ); /// Errors returned by functions the BPF Loader registers with the VM #[derive(Debug, Error, PartialEq)] pub enum BpfError { #[error("{0}")] VerifierError(#[from] VerifierError), #[error("{0}")] SyscallError(#[from] SyscallError), } impl UserDefinedError for BpfError {} fn map_ebpf_error(invoke_context: &InvokeContext, e: EbpfError<BpfError>) -> InstructionError { ic_msg!(invoke_context, "{}", e); InstructionError::InvalidAccountData } mod executor_metrics { #[derive(Debug, Default)] pub struct CreateMetrics { pub program_id: String, pub load_elf_us: u64, pub verify_code_us: u64, pub jit_compile_us: u64, } impl CreateMetrics { pub fn submit_datapoint(&self) { datapoint_trace!( "create_executor_trace", ("program_id", self.program_id, String), ("load_elf_us", self.load_elf_us, i64), ("verify_code_us", self.verify_code_us, i64), ("jit_compile_us", self.jit_compile_us, i64), ); } } } pub fn create_executor( programdata_account_index: usize, programdata_offset: usize, invoke_context: &mut InvokeContext, use_jit: bool, reject_deployment_of_broken_elfs: bool, ) -> Result<Arc<BpfExecutor>, InstructionError> { let mut register_syscalls_time = Measure::start("register_syscalls_time"); let register_syscall_result = syscalls::register_syscalls(invoke_context); register_syscalls_time.stop(); invoke_context.timings.create_executor_register_syscalls_us = invoke_context .timings .create_executor_register_syscalls_us .saturating_add(register_syscalls_time.as_us()); let syscall_registry = register_syscall_result.map_err(|e| { ic_msg!(invoke_context, "Failed to register syscalls: {}", e); InstructionError::ProgramEnvironmentSetupFailure })?; let compute_budget = invoke_context.get_compute_budget(); let config = Config { max_call_depth: compute_budget.max_call_depth, stack_frame_size: compute_budget.stack_frame_size, enable_instruction_tracing: log_enabled!(Trace), disable_deprecated_load_instructions: reject_deployment_of_broken_elfs && invoke_context .feature_set .is_active(&disable_bpf_deprecated_load_instructions::id()), disable_unresolved_symbols_at_runtime: invoke_context .feature_set .is_active(&disable_bpf_unresolved_symbols_at_runtime::id()), reject_broken_elfs: reject_deployment_of_broken_elfs, ..Config::default() }; let mut create_executor_metrics = executor_metrics::CreateMetrics::default(); let mut executable = { let keyed_accounts = invoke_context.get_keyed_accounts()?; let programdata = keyed_account_at_index(keyed_accounts, programdata_account_index)?; create_executor_metrics.program_id = programdata.unsigned_key().to_string(); let mut load_elf_time = Measure::start("load_elf_time"); let executable = Executable::<BpfError, ThisInstructionMeter>::from_elf( programdata .try_account_ref()? .data() .get(programdata_offset..) .ok_or(InstructionError::AccountDataTooSmall)?, None, config, syscall_registry, ); load_elf_time.stop(); create_executor_metrics.load_elf_us = load_elf_time.as_us(); invoke_context.timings.create_executor_load_elf_us = invoke_context .timings .create_executor_load_elf_us .saturating_add(create_executor_metrics.load_elf_us); executable } .map_err(|e| map_ebpf_error(invoke_context, e))?; let text_bytes = executable.get_text_bytes().1; let mut verify_code_time = Measure::start("verify_code_time"); verifier::check(text_bytes, &config) .map_err(|e| map_ebpf_error(invoke_context, EbpfError::UserError(e.into())))?; verify_code_time.stop(); create_executor_metrics.verify_code_us = verify_code_time.as_us(); invoke_context.timings.create_executor_verify_code_us = invoke_context .timings .create_executor_verify_code_us .saturating_add(create_executor_metrics.verify_code_us); if use_jit { let mut jit_compile_time = Measure::start("jit_compile_time"); let jit_compile_result = Executable::<BpfError, ThisInstructionMeter>::jit_compile(&mut executable); jit_compile_time.stop(); create_executor_metrics.jit_compile_us = jit_compile_time.as_us(); invoke_context.timings.create_executor_jit_compile_us = invoke_context .timings .create_executor_jit_compile_us .saturating_add(create_executor_metrics.jit_compile_us); if let Err(err) = jit_compile_result { ic_msg!(invoke_context, "Failed to compile program {:?}", err); return Err(InstructionError::ProgramFailedToCompile); } } create_executor_metrics.submit_datapoint(); Ok(Arc::new(BpfExecutor { executable, use_jit, })) } fn write_program_data( program_account_index: usize, program_data_offset: usize, bytes: &[u8], invoke_context: &mut InvokeContext, ) -> Result<(), InstructionError> { let keyed_accounts = invoke_context.get_keyed_accounts()?; let program = keyed_account_at_index(keyed_accounts, program_account_index)?; let mut account = program.try_account_ref_mut()?; let data = &mut account.data_as_mut_slice(); let len = bytes.len(); if data.len() < program_data_offset.saturating_add(len) { ic_msg!( invoke_context, "Write overflow: {} < {}", data.len(), program_data_offset.saturating_add(len), ); return Err(InstructionError::AccountDataTooSmall); } data.get_mut(program_data_offset..program_data_offset.saturating_add(len)) .ok_or(InstructionError::AccountDataTooSmall)? .copy_from_slice(bytes); Ok(()) } fn check_loader_id(id: &Pubkey) -> bool { bpf_loader::check_id(id) || bpf_loader_deprecated::check_id(id) || bpf_loader_upgradeable::check_id(id) } /// Create the BPF virtual machine pub fn create_vm<'a, 'b>( program: &'a Pin<Box<Executable<BpfError, ThisInstructionMeter>>>, parameter_bytes: &mut [u8], invoke_context: &'a mut InvokeContext<'b>, orig_data_lens: &'a [usize], ) -> Result<EbpfVm<'a, BpfError, ThisInstructionMeter>, EbpfError<BpfError>> { let compute_budget = invoke_context.get_compute_budget(); let heap_size = compute_budget.heap_size.unwrap_or(HEAP_LENGTH); if invoke_context .feature_set .is_active(&requestable_heap_size::id()) { let _ = invoke_context.get_compute_meter().borrow_mut().consume( ((heap_size as u64).saturating_div(32_u64.saturating_mul(1024))) .saturating_sub(1) .saturating_mul(compute_budget.heap_cost), ); } let mut heap = AlignedMemory::new_with_size(compute_budget.heap_size.unwrap_or(HEAP_LENGTH), HOST_ALIGN); let mut vm = EbpfVm::new(program, heap.as_slice_mut(), parameter_bytes)?; syscalls::bind_syscall_context_objects(&mut vm, invoke_context, heap, orig_data_lens)?; Ok(vm) } pub fn process_instruction( first_instruction_account: usize, instruction_data: &[u8], invoke_context: &mut InvokeContext, ) -> Result<(), InstructionError> { process_instruction_common( first_instruction_account, instruction_data, invoke_context, false, ) } pub fn process_instruction_jit( first_instruction_account: usize, instruction_data: &[u8], invoke_context: &mut InvokeContext, ) -> Result<(), InstructionError> { process_instruction_common( first_instruction_account, instruction_data, invoke_context, true, ) } fn process_instruction_common( first_instruction_account: usize, instruction_data: &[u8], invoke_context: &mut InvokeContext, use_jit: bool, ) -> Result<(), InstructionError> { let log_collector = invoke_context.get_log_collector(); let transaction_context = &invoke_context.transaction_context; let instruction_context = transaction_context.get_current_instruction_context()?; let program_id = instruction_context.get_program_key(transaction_context)?; let keyed_accounts = invoke_context.get_keyed_accounts()?; let first_account = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let second_account = keyed_account_at_index(keyed_accounts, first_instruction_account.saturating_add(1)); let (program, next_first_instruction_account) = if first_account.unsigned_key() == program_id { (first_account, first_instruction_account) } else if second_account .as_ref() .map(|keyed_account| keyed_account.unsigned_key() == program_id) .unwrap_or(false) { (second_account?, first_instruction_account.saturating_add(1)) } else { if first_account.executable()? { ic_logger_msg!(log_collector, "BPF loader is executable"); return Err(InstructionError::IncorrectProgramId); } (first_account, first_instruction_account) }; if program.executable()? { // First instruction account can only be zero if called from CPI, which // means stack height better be greater than one debug_assert_eq!( first_instruction_account == 0, invoke_context.get_stack_height() > 1 ); if !check_loader_id(&program.owner()?) { ic_logger_msg!( log_collector, "Executable account not owned by the BPF loader" ); return Err(InstructionError::IncorrectProgramId); } let program_data_offset = if bpf_loader_upgradeable::check_id(&program.owner()?) { if let UpgradeableLoaderState::Program { programdata_address, } = program.state()? { if programdata_address != *first_account.unsigned_key() { ic_logger_msg!( log_collector, "Wrong ProgramData account for this Program account" ); return Err(InstructionError::InvalidArgument); } if !matches!( first_account.state()?, UpgradeableLoaderState::ProgramData { slot: _, upgrade_authority_address: _, } ) { ic_logger_msg!(log_collector, "Program has been closed"); return Err(InstructionError::InvalidAccountData); } UpgradeableLoaderState::programdata_data_offset()? } else { ic_logger_msg!(log_collector, "Invalid Program account"); return Err(InstructionError::InvalidAccountData); } } else { 0 }; let mut get_or_create_executor_time = Measure::start("get_or_create_executor_time"); let executor = match invoke_context.get_executor(program_id) { Some(executor) => executor, None => { let executor = create_executor( first_instruction_account, program_data_offset, invoke_context, use_jit, false, )?; let transaction_context = &invoke_context.transaction_context; let instruction_context = transaction_context.get_current_instruction_context()?; let program_id = instruction_context.get_program_key(transaction_context)?; invoke_context.add_executor(program_id, executor.clone()); executor } }; get_or_create_executor_time.stop(); saturating_add_assign!( invoke_context.timings.get_or_create_executor_us, get_or_create_executor_time.as_us() ); executor.execute( next_first_instruction_account, instruction_data, invoke_context, ) } else { debug_assert_eq!(first_instruction_account, 1); let disable_deprecated_loader = invoke_context .feature_set .is_active(&disable_deprecated_loader::id()); if bpf_loader_upgradeable::check_id(program_id) { process_loader_upgradeable_instruction( first_instruction_account, instruction_data, invoke_context, use_jit, ) } else if bpf_loader::check_id(program_id) || (!disable_deprecated_loader && bpf_loader_deprecated::check_id(program_id)) { process_loader_instruction( first_instruction_account, instruction_data, invoke_context, use_jit, ) } else if disable_deprecated_loader && bpf_loader_deprecated::check_id(program_id) { ic_logger_msg!(log_collector, "Deprecated loader is no longer supported"); Err(InstructionError::UnsupportedProgramId) } else { ic_logger_msg!(log_collector, "Invalid BPF loader id"); Err(InstructionError::IncorrectProgramId) } } } fn process_loader_upgradeable_instruction( first_instruction_account: usize, instruction_data: &[u8], invoke_context: &mut InvokeContext, use_jit: bool, ) -> Result<(), InstructionError> { let log_collector = invoke_context.get_log_collector(); let transaction_context = &invoke_context.transaction_context; let instruction_context = transaction_context.get_current_instruction_context()?; let program_id = instruction_context.get_program_key(transaction_context)?; let keyed_accounts = invoke_context.get_keyed_accounts()?; match limited_deserialize(instruction_data)? { UpgradeableLoaderInstruction::InitializeBuffer => { let buffer = keyed_account_at_index(keyed_accounts, first_instruction_account)?; if UpgradeableLoaderState::Uninitialized != buffer.state()? { ic_logger_msg!(log_collector, "Buffer account already initialized"); return Err(InstructionError::AccountAlreadyInitialized); } let authority = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(1), )?; buffer.set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(*authority.unsigned_key()), })?; } UpgradeableLoaderInstruction::Write { offset, bytes } => { let buffer = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let authority = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(1), )?; if let UpgradeableLoaderState::Buffer { authority_address } = buffer.state()? { if authority_address.is_none() { ic_logger_msg!(log_collector, "Buffer is immutable"); return Err(InstructionError::Immutable); // TODO better error code } if authority_address != Some(*authority.unsigned_key()) { ic_logger_msg!(log_collector, "Incorrect buffer authority provided"); return Err(InstructionError::IncorrectAuthority); } if authority.signer_key().is_none() { ic_logger_msg!(log_collector, "Buffer authority did not sign"); return Err(InstructionError::MissingRequiredSignature); } } else { ic_logger_msg!(log_collector, "Invalid Buffer account"); return Err(InstructionError::InvalidAccountData); } write_program_data( first_instruction_account, UpgradeableLoaderState::buffer_data_offset()?.saturating_add(offset as usize), &bytes, invoke_context, )?; } UpgradeableLoaderInstruction::DeployWithMaxDataLen { max_data_len } => { let payer = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let programdata = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(1), )?; let program = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(2), )?; let buffer = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(3), )?; let rent = get_sysvar_with_account_check::rent( keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(4), )?, invoke_context, )?; let clock = get_sysvar_with_account_check::clock( keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(5), )?, invoke_context, )?; let authority = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(7), )?; let upgrade_authority_address = Some(*authority.unsigned_key()); let upgrade_authority_signer = authority.signer_key().is_none(); // Verify Program account if UpgradeableLoaderState::Uninitialized != program.state()? { ic_logger_msg!(log_collector, "Program account already initialized"); return Err(InstructionError::AccountAlreadyInitialized); } if program.data_len()? < UpgradeableLoaderState::program_len()? { ic_logger_msg!(log_collector, "Program account too small"); return Err(InstructionError::AccountDataTooSmall); } if program.lamports()? < rent.minimum_balance(program.data_len()?) { ic_logger_msg!(log_collector, "Program account not rent-exempt"); return Err(InstructionError::ExecutableAccountNotRentExempt); } let new_program_id = *program.unsigned_key(); // Verify Buffer account if let UpgradeableLoaderState::Buffer { authority_address } = buffer.state()? { if authority_address != upgrade_authority_address { ic_logger_msg!(log_collector, "Buffer and upgrade authority don't match"); return Err(InstructionError::IncorrectAuthority); } if upgrade_authority_signer { ic_logger_msg!(log_collector, "Upgrade authority did not sign"); return Err(InstructionError::MissingRequiredSignature); } } else { ic_logger_msg!(log_collector, "Invalid Buffer account"); return Err(InstructionError::InvalidArgument); } let buffer_data_offset = UpgradeableLoaderState::buffer_data_offset()?; let buffer_data_len = buffer.data_len()?.saturating_sub(buffer_data_offset); let programdata_data_offset = UpgradeableLoaderState::programdata_data_offset()?; let programdata_len = UpgradeableLoaderState::programdata_len(max_data_len)?; if buffer.data_len()? < UpgradeableLoaderState::buffer_data_offset()? || buffer_data_len == 0 { ic_logger_msg!(log_collector, "Buffer account too small"); return Err(InstructionError::InvalidAccountData); } if max_data_len < buffer_data_len { ic_logger_msg!( log_collector, "Max data length is too small to hold Buffer data" ); return Err(InstructionError::AccountDataTooSmall); } if programdata_len > MAX_PERMITTED_DATA_LENGTH as usize { ic_logger_msg!(log_collector, "Max data length is too large"); return Err(InstructionError::InvalidArgument); } // Create ProgramData account let (derived_address, bump_seed) = Pubkey::find_program_address(&[new_program_id.as_ref()], program_id); if derived_address != *programdata.unsigned_key() { ic_logger_msg!(log_collector, "ProgramData address is not derived"); return Err(InstructionError::InvalidArgument); } let predrain_buffer = invoke_context .feature_set .is_active(&reduce_required_deploy_balance::id()); if predrain_buffer { // Drain the Buffer account to payer before paying for programdata account payer .try_account_ref_mut()? .checked_add_lamports(buffer.lamports()?)?; buffer.try_account_ref_mut()?.set_lamports(0); } let mut instruction = system_instruction::create_account( payer.unsigned_key(), programdata.unsigned_key(), 1.max(rent.minimum_balance(programdata_len)), programdata_len as u64, program_id, ); // pass an extra account to avoid the overly strict UnbalancedInstruction error instruction .accounts .push(AccountMeta::new(*buffer.unsigned_key(), false)); let transaction_context = &invoke_context.transaction_context; let instruction_context = transaction_context.get_current_instruction_context()?; let caller_program_id = instruction_context.get_program_key(transaction_context)?; let signers = [&[new_program_id.as_ref(), &[bump_seed]]] .iter() .map(|seeds| Pubkey::create_program_address(*seeds, caller_program_id)) .collect::<Result<Vec<Pubkey>, solana_sdk::pubkey::PubkeyError>>()?; invoke_context.native_invoke(instruction, signers.as_slice())?; // Load and verify the program bits let executor = create_executor( first_instruction_account.saturating_add(3), buffer_data_offset, invoke_context, use_jit, true, )?; invoke_context.update_executor(&new_program_id, executor); let keyed_accounts = invoke_context.get_keyed_accounts()?; let payer = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let programdata = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(1), )?; let program = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(2), )?; let buffer = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(3), )?; // Update the ProgramData account and record the program bits programdata.set_state(&UpgradeableLoaderState::ProgramData { slot: clock.slot, upgrade_authority_address, })?; programdata .try_account_ref_mut()? .data_as_mut_slice() .get_mut( programdata_data_offset ..programdata_data_offset.saturating_add(buffer_data_len), ) .ok_or(InstructionError::AccountDataTooSmall)? .copy_from_slice( buffer .try_account_ref()? .data() .get(buffer_data_offset..) .ok_or(InstructionError::AccountDataTooSmall)?, ); // Update the Program account program.set_state(&UpgradeableLoaderState::Program { programdata_address: *programdata.unsigned_key(), })?; program.try_account_ref_mut()?.set_executable(true); if !predrain_buffer { // Drain the Buffer account back to the payer payer .try_account_ref_mut()? .checked_add_lamports(buffer.lamports()?)?; buffer.try_account_ref_mut()?.set_lamports(0); } ic_logger_msg!(log_collector, "Deployed program {:?}", new_program_id); } UpgradeableLoaderInstruction::Upgrade => { let programdata = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let program = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(1), )?; let buffer = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(2), )?; let rent = get_sysvar_with_account_check::rent( keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(4), )?, invoke_context, )?; let clock = get_sysvar_with_account_check::clock( keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(5), )?, invoke_context, )?; let authority = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(6), )?; // Verify Program account if !program.executable()? { ic_logger_msg!(log_collector, "Program account not executable"); return Err(InstructionError::AccountNotExecutable); } if !program.is_writable() { ic_logger_msg!(log_collector, "Program account not writeable"); return Err(InstructionError::InvalidArgument); } if &program.owner()? != program_id { ic_logger_msg!(log_collector, "Program account not owned by loader"); return Err(InstructionError::IncorrectProgramId); } if let UpgradeableLoaderState::Program { programdata_address, } = program.state()? { if programdata_address != *programdata.unsigned_key() { ic_logger_msg!(log_collector, "Program and ProgramData account mismatch"); return Err(InstructionError::InvalidArgument); } } else { ic_logger_msg!(log_collector, "Invalid Program account"); return Err(InstructionError::InvalidAccountData); } let new_program_id = *program.unsigned_key(); // Verify Buffer account if let UpgradeableLoaderState::Buffer { authority_address } = buffer.state()? { if authority_address != Some(*authority.unsigned_key()) { ic_logger_msg!(log_collector, "Buffer and upgrade authority don't match"); return Err(InstructionError::IncorrectAuthority); } if authority.signer_key().is_none() { ic_logger_msg!(log_collector, "Upgrade authority did not sign"); return Err(InstructionError::MissingRequiredSignature); } } else { ic_logger_msg!(log_collector, "Invalid Buffer account"); return Err(InstructionError::InvalidArgument); } let buffer_data_offset = UpgradeableLoaderState::buffer_data_offset()?; let buffer_data_len = buffer.data_len()?.saturating_sub(buffer_data_offset); let programdata_data_offset = UpgradeableLoaderState::programdata_data_offset()?; let programdata_balance_required = 1.max(rent.minimum_balance(programdata.data_len()?)); if buffer.data_len()? < UpgradeableLoaderState::buffer_data_offset()? || buffer_data_len == 0 { ic_logger_msg!(log_collector, "Buffer account too small"); return Err(InstructionError::InvalidAccountData); } // Verify ProgramData account if programdata.data_len()? < UpgradeableLoaderState::programdata_len(buffer_data_len)? { ic_logger_msg!(log_collector, "ProgramData account not large enough"); return Err(InstructionError::AccountDataTooSmall); } if programdata.lamports()?.saturating_add(buffer.lamports()?) < programdata_balance_required { ic_logger_msg!( log_collector, "Buffer account balance too low to fund upgrade" ); return Err(InstructionError::InsufficientFunds); } if let UpgradeableLoaderState::ProgramData { slot: _, upgrade_authority_address, } = programdata.state()? { if upgrade_authority_address.is_none() { ic_logger_msg!(log_collector, "Program not upgradeable"); return Err(InstructionError::Immutable); } if upgrade_authority_address != Some(*authority.unsigned_key()) { ic_logger_msg!(log_collector, "Incorrect upgrade authority provided"); return Err(InstructionError::IncorrectAuthority); } if authority.signer_key().is_none() { ic_logger_msg!(log_collector, "Upgrade authority did not sign"); return Err(InstructionError::MissingRequiredSignature); } } else { ic_logger_msg!(log_collector, "Invalid ProgramData account"); return Err(InstructionError::InvalidAccountData); } // Load and verify the program bits let executor = create_executor( first_instruction_account.saturating_add(2), buffer_data_offset, invoke_context, use_jit, true, )?; invoke_context.update_executor(&new_program_id, executor); let keyed_accounts = invoke_context.get_keyed_accounts()?; let programdata = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let buffer = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(2), )?; let spill = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(3), )?; let authority = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(6), )?; // Update the ProgramData account, record the upgraded data, and zero // the rest programdata.set_state(&UpgradeableLoaderState::ProgramData { slot: clock.slot, upgrade_authority_address: Some(*authority.unsigned_key()), })?; programdata .try_account_ref_mut()? .data_as_mut_slice() .get_mut( programdata_data_offset ..programdata_data_offset.saturating_add(buffer_data_len), ) .ok_or(InstructionError::AccountDataTooSmall)? .copy_from_slice( buffer .try_account_ref()? .data() .get(buffer_data_offset..) .ok_or(InstructionError::AccountDataTooSmall)?, ); programdata .try_account_ref_mut()? .data_as_mut_slice() .get_mut(programdata_data_offset.saturating_add(buffer_data_len)..) .ok_or(InstructionError::AccountDataTooSmall)? .fill(0); // Fund ProgramData to rent-exemption, spill the rest spill.try_account_ref_mut()?.checked_add_lamports( programdata .lamports()? .saturating_add(buffer.lamports()?) .saturating_sub(programdata_balance_required), )?; buffer.try_account_ref_mut()?.set_lamports(0); programdata .try_account_ref_mut()? .set_lamports(programdata_balance_required); ic_logger_msg!(log_collector, "Upgraded program {:?}", new_program_id); } UpgradeableLoaderInstruction::SetAuthority => { let account = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let present_authority = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(1), )?; let new_authority = keyed_account_at_index(keyed_accounts, first_instruction_account.saturating_add(2)) .ok() .map(|account| account.unsigned_key()); match account.state()? { UpgradeableLoaderState::Buffer { authority_address } => { if new_authority.is_none() { ic_logger_msg!(log_collector, "Buffer authority is not optional"); return Err(InstructionError::IncorrectAuthority); } if authority_address.is_none() { ic_logger_msg!(log_collector, "Buffer is immutable"); return Err(InstructionError::Immutable); } if authority_address != Some(*present_authority.unsigned_key()) { ic_logger_msg!(log_collector, "Incorrect buffer authority provided"); return Err(InstructionError::IncorrectAuthority); } if present_authority.signer_key().is_none() { ic_logger_msg!(log_collector, "Buffer authority did not sign"); return Err(InstructionError::MissingRequiredSignature); } account.set_state(&UpgradeableLoaderState::Buffer { authority_address: new_authority.cloned(), })?; } UpgradeableLoaderState::ProgramData { slot, upgrade_authority_address, } => { if upgrade_authority_address.is_none() { ic_logger_msg!(log_collector, "Program not upgradeable"); return Err(InstructionError::Immutable); } if upgrade_authority_address != Some(*present_authority.unsigned_key()) { ic_logger_msg!(log_collector, "Incorrect upgrade authority provided"); return Err(InstructionError::IncorrectAuthority); } if present_authority.signer_key().is_none() { ic_logger_msg!(log_collector, "Upgrade authority did not sign"); return Err(InstructionError::MissingRequiredSignature); } account.set_state(&UpgradeableLoaderState::ProgramData { slot, upgrade_authority_address: new_authority.cloned(), })?; } _ => { ic_logger_msg!(log_collector, "Account does not support authorities"); return Err(InstructionError::InvalidArgument); } } ic_logger_msg!(log_collector, "New authority {:?}", new_authority); } UpgradeableLoaderInstruction::Close => { let close_account = keyed_account_at_index(keyed_accounts, first_instruction_account)?; let recipient_account = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(1), )?; if close_account.unsigned_key() == recipient_account.unsigned_key() { ic_logger_msg!( log_collector, "Recipient is the same as the account being closed" ); return Err(InstructionError::InvalidArgument); } match close_account.state()? { UpgradeableLoaderState::Uninitialized => { recipient_account .try_account_ref_mut()? .checked_add_lamports(close_account.lamports()?)?; close_account.try_account_ref_mut()?.set_lamports(0); ic_logger_msg!( log_collector, "Closed Uninitialized {}", close_account.unsigned_key() ); } UpgradeableLoaderState::Buffer { authority_address } => { let authority = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(2), )?; common_close_account( &authority_address, authority, close_account, recipient_account, &log_collector, )?; ic_logger_msg!( log_collector, "Closed Buffer {}", close_account.unsigned_key() ); } UpgradeableLoaderState::ProgramData { slot: _, upgrade_authority_address: authority_address, } => { let program_account = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(3), )?; if !program_account.is_writable() { ic_logger_msg!(log_collector, "Program account is not writable"); return Err(InstructionError::InvalidArgument); } if &program_account.owner()? != program_id { ic_logger_msg!(log_collector, "Program account not owned by loader"); return Err(InstructionError::IncorrectProgramId); } match program_account.state()? { UpgradeableLoaderState::Program { programdata_address, } => { if programdata_address != *close_account.unsigned_key() { ic_logger_msg!( log_collector, "ProgramData account does not match ProgramData account" ); return Err(InstructionError::InvalidArgument); } let authority = keyed_account_at_index( keyed_accounts, first_instruction_account.saturating_add(2), )?; common_close_account( &authority_address, authority, close_account, recipient_account, &log_collector, )?; } _ => { ic_logger_msg!(log_collector, "Invalid Program account"); return Err(InstructionError::InvalidArgument); } } ic_logger_msg!( log_collector, "Closed Program {}", program_account.unsigned_key() ); } _ => { ic_logger_msg!(log_collector, "Account does not support closing"); return Err(InstructionError::InvalidArgument); } } } } Ok(()) } fn common_close_account( authority_address: &Option<Pubkey>, authority_account: &KeyedAccount, close_account: &KeyedAccount, recipient_account: &KeyedAccount, log_collector: &Option<Rc<RefCell<LogCollector>>>, ) -> Result<(), InstructionError> { if authority_address.is_none() { ic_logger_msg!(log_collector, "Account is immutable"); return Err(InstructionError::Immutable); } if *authority_address != Some(*authority_account.unsigned_key()) { ic_logger_msg!(log_collector, "Incorrect authority provided"); return Err(InstructionError::IncorrectAuthority); } if authority_account.signer_key().is_none() { ic_logger_msg!(log_collector, "Authority did not sign"); return Err(InstructionError::MissingRequiredSignature); } recipient_account .try_account_ref_mut()? .checked_add_lamports(close_account.lamports()?)?; close_account.try_account_ref_mut()?.set_lamports(0); close_account.set_state(&UpgradeableLoaderState::Uninitialized)?; Ok(()) } fn process_loader_instruction( first_instruction_account: usize, instruction_data: &[u8], invoke_context: &mut InvokeContext, use_jit: bool, ) -> Result<(), InstructionError> { let transaction_context = &invoke_context.transaction_context; let instruction_context = transaction_context.get_current_instruction_context()?; let program_id = instruction_context.get_program_key(transaction_context)?; let keyed_accounts = invoke_context.get_keyed_accounts()?; let program = keyed_account_at_index(keyed_accounts, first_instruction_account)?; if program.owner()? != *program_id { ic_msg!( invoke_context, "Executable account not owned by the BPF loader" ); return Err(InstructionError::IncorrectProgramId); } match limited_deserialize(instruction_data)? { LoaderInstruction::Write { offset, bytes } => { if program.signer_key().is_none() { ic_msg!(invoke_context, "Program account did not sign"); return Err(InstructionError::MissingRequiredSignature); } write_program_data( first_instruction_account, offset as usize, &bytes, invoke_context, )?; } LoaderInstruction::Finalize => { if program.signer_key().is_none() { ic_msg!(invoke_context, "key[0] did not sign the transaction"); return Err(InstructionError::MissingRequiredSignature); } let executor = create_executor(first_instruction_account, 0, invoke_context, use_jit, true)?; let keyed_accounts = invoke_context.get_keyed_accounts()?; let program = keyed_account_at_index(keyed_accounts, first_instruction_account)?; invoke_context.update_executor(program.unsigned_key(), executor); program.try_account_ref_mut()?.set_executable(true); ic_msg!( invoke_context, "Finalized account {:?}", program.unsigned_key() ); } } Ok(()) } /// Passed to the VM to enforce the compute budget pub struct ThisInstructionMeter { pub compute_meter: Rc<RefCell<ComputeMeter>>, } impl ThisInstructionMeter { fn new(compute_meter: Rc<RefCell<ComputeMeter>>) -> Self { Self { compute_meter } } } impl InstructionMeter for ThisInstructionMeter { fn consume(&mut self, amount: u64) { // 1 to 1 instruction to compute unit mapping // ignore error, Ebpf will bail if exceeded let _ = self.compute_meter.borrow_mut().consume(amount); } fn get_remaining(&self) -> u64
} /// BPF Loader's Executor implementation pub struct BpfExecutor { executable: Pin<Box<Executable<BpfError, ThisInstructionMeter>>>, use_jit: bool, } // Well, implement Debug for solana_rbpf::vm::Executable in solana-rbpf... impl Debug for BpfExecutor { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "BpfExecutor({:p})", self) } } impl Executor for BpfExecutor { fn execute<'a, 'b>( &self, _first_instruction_account: usize, _instruction_data: &[u8], invoke_context: &'a mut InvokeContext<'b>, ) -> Result<(), InstructionError> { let log_collector = invoke_context.get_log_collector(); let compute_meter = invoke_context.get_compute_meter(); let stack_height = invoke_context.get_stack_height(); let transaction_context = &invoke_context.transaction_context; let instruction_context = transaction_context.get_current_instruction_context()?; let program_id = *instruction_context.get_program_key(transaction_context)?; let mut serialize_time = Measure::start("serialize"); let (mut parameter_bytes, account_lengths) = serialize_parameters(invoke_context.transaction_context, instruction_context)?; serialize_time.stop(); let mut create_vm_time = Measure::start("create_vm"); let mut execute_time; let execution_result = { let mut vm = match create_vm( &self.executable, parameter_bytes.as_slice_mut(), invoke_context, &account_lengths, ) { Ok(info) => info, Err(e) => { ic_logger_msg!(log_collector, "Failed to create BPF VM: {}", e); return Err(InstructionError::ProgramEnvironmentSetupFailure); } }; create_vm_time.stop(); execute_time = Measure::start("execute"); stable_log::program_invoke(&log_collector, &program_id, stack_height); let mut instruction_meter = ThisInstructionMeter::new(compute_meter.clone()); let before = compute_meter.borrow().get_remaining(); let result = if self.use_jit { vm.execute_program_jit(&mut instruction_meter) } else { vm.execute_program_interpreted(&mut instruction_meter) }; let after = compute_meter.borrow().get_remaining(); ic_logger_msg!( log_collector, "Program {} consumed {} of {} compute units", &program_id, before.saturating_sub(after), before ); if log_enabled!(Trace) { let mut trace_buffer = Vec::<u8>::new(); let analysis = Analysis::from_executable(&self.executable); vm.get_tracer().write(&mut trace_buffer, &analysis).unwrap(); let trace_string = String::from_utf8(trace_buffer).unwrap(); trace!("BPF Program Instruction Trace:\n{}", trace_string); } drop(vm); let (_returned_from_program_id, return_data) = invoke_context.transaction_context.get_return_data(); if !return_data.is_empty() { stable_log::program_return(&log_collector, &program_id, return_data); } match result { Ok(status) if status != SUCCESS => { let error: InstructionError = if status == MAX_ACCOUNTS_DATA_SIZE_EXCEEDED && !invoke_context .feature_set .is_active(&cap_accounts_data_len::id()) { // Until the cap_accounts_data_len feature is enabled, map the // MAX_ACCOUNTS_DATA_SIZE_EXCEEDED error to InvalidError InstructionError::InvalidError } else { status.into() }; stable_log::program_failure(&log_collector, &program_id, &error); Err(error) } Err(error) => { let error = match error { EbpfError::UserError(BpfError::SyscallError( SyscallError::InstructionError(error), )) => error, err => { ic_logger_msg!(log_collector, "Program failed to complete: {}", err); InstructionError::ProgramFailedToComplete } }; stable_log::program_failure(&log_collector, &program_id, &error); Err(error) } _ => Ok(()), } }; execute_time.stop(); let mut deserialize_time = Measure::start("deserialize"); let execute_or_deserialize_result = execution_result.and_then(|_| { deserialize_parameters( invoke_context.transaction_context, invoke_context .transaction_context .get_current_instruction_context()?, parameter_bytes.as_slice(), &account_lengths, invoke_context .feature_set .is_active(&do_support_realloc::id()), ) }); deserialize_time.stop(); // Update the timings let timings = &mut invoke_context.timings; timings.serialize_us = timings.serialize_us.saturating_add(serialize_time.as_us()); timings.create_vm_us = timings.create_vm_us.saturating_add(create_vm_time.as_us()); timings.execute_us = timings.execute_us.saturating_add(execute_time.as_us()); timings.deserialize_us = timings .deserialize_us .saturating_add(deserialize_time.as_us()); if execute_or_deserialize_result.is_ok() { stable_log::program_success(&log_collector, &program_id); } execute_or_deserialize_result } } #[cfg(test)] mod tests { use { super::*, rand::Rng, solana_program_runtime::invoke_context::mock_process_instruction, solana_rbpf::vm::SyscallRegistry, solana_runtime::{bank::Bank, bank_client::BankClient}, solana_sdk::{ account::{ create_account_shared_data_for_test as create_account_for_test, AccountSharedData, }, account_utils::StateMut, client::SyncClient, clock::Clock, feature_set::FeatureSet, genesis_config::create_genesis_config, instruction::{AccountMeta, Instruction, InstructionError}, message::Message, native_token::LAMPORTS_PER_SOL, pubkey::Pubkey, rent::Rent, signature::{Keypair, Signer}, system_program, sysvar, transaction::TransactionError, }, std::{fs::File, io::Read, ops::Range, sync::Arc}, }; struct TestInstructionMeter { remaining: u64, } impl InstructionMeter for TestInstructionMeter { fn consume(&mut self, amount: u64) { self.remaining = self.remaining.saturating_sub(amount); } fn get_remaining(&self) -> u64 { self.remaining } } fn process_instruction( loader_id: &Pubkey, program_indices: &[usize], instruction_data: &[u8], transaction_accounts: Vec<(Pubkey, AccountSharedData)>, instruction_accounts: Vec<AccountMeta>, expected_result: Result<(), InstructionError>, ) -> Vec<AccountSharedData> { mock_process_instruction( loader_id, program_indices.to_vec(), instruction_data, transaction_accounts, instruction_accounts, expected_result, super::process_instruction, ) } fn load_program_account_from_elf(loader_id: &Pubkey, path: &str) -> AccountSharedData { let mut file = File::open(path).expect("file open failed"); let mut elf = Vec::new(); file.read_to_end(&mut elf).unwrap(); let rent = Rent::default(); let mut program_account = AccountSharedData::new(rent.minimum_balance(elf.len()), 0, loader_id); program_account.set_data(elf); program_account.set_executable(true); program_account } #[test] #[should_panic(expected = "ExceededMaxInstructions(31, 10)")] fn test_bpf_loader_non_terminating_program() { #[rustfmt::skip] let program = &[ 0x07, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, // r6 + 1 0x05, 0x00, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, // goto -2 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // exit ]; let input = &mut [0x00]; let mut bpf_functions = std::collections::BTreeMap::<u32, (usize, String)>::new(); solana_rbpf::elf::register_bpf_function(&mut bpf_functions, 0, "entrypoint", false) .unwrap(); let program = Executable::<BpfError, TestInstructionMeter>::from_text_bytes( program, None, Config::default(), SyscallRegistry::default(), bpf_functions, ) .unwrap(); let mut vm = EbpfVm::<BpfError, TestInstructionMeter>::new(&program, &mut [], input).unwrap(); let mut instruction_meter = TestInstructionMeter { remaining: 10 }; vm.execute_program_interpreted(&mut instruction_meter) .unwrap(); } #[test] #[should_panic(expected = "LDDWCannotBeLast")] fn test_bpf_loader_check_load_dw() { let prog = &[ 0x18, 0x00, 0x00, 0x00, 0x88, 0x77, 0x66, 0x55, // first half of lddw ]; verifier::check(prog, &Config::default()).unwrap(); } #[test] fn test_bpf_loader_write() { let loader_id = bpf_loader::id(); let program_id = Pubkey::new_unique(); let mut program_account = AccountSharedData::new(1, 0, &loader_id); let instruction_data = bincode::serialize(&LoaderInstruction::Write { offset: 3, bytes: vec![1, 2, 3], }) .unwrap(); // Case: No program account process_instruction( &loader_id, &[], &instruction_data, Vec::new(), Vec::new(), Err(InstructionError::NotEnoughAccountKeys), ); // Case: Not signed process_instruction( &loader_id, &[], &instruction_data, vec![(program_id, program_account.clone())], vec![AccountMeta { pubkey: program_id, is_signer: false, is_writable: false, }], Err(InstructionError::MissingRequiredSignature), ); // Case: Write bytes to an offset program_account.set_data(vec![0; 6]); let accounts = process_instruction( &loader_id, &[], &instruction_data, vec![(program_id, program_account.clone())], vec![AccountMeta { pubkey: program_id, is_signer: true, is_writable: false, }], Ok(()), ); assert_eq!(&vec![0, 0, 0, 1, 2, 3], accounts.first().unwrap().data()); // Case: Overflow program_account.set_data(vec![0; 5]); process_instruction( &loader_id, &[], &instruction_data, vec![(program_id, program_account)], vec![AccountMeta { pubkey: program_id, is_signer: true, is_writable: false, }], Err(InstructionError::AccountDataTooSmall), ); } #[test] fn test_bpf_loader_finalize() { let loader_id = bpf_loader::id(); let program_id = Pubkey::new_unique(); let mut program_account = load_program_account_from_elf(&loader_id, "test_elfs/noop_aligned.so"); program_account.set_executable(false); let instruction_data = bincode::serialize(&LoaderInstruction::Finalize).unwrap(); // Case: No program account process_instruction( &loader_id, &[], &instruction_data, Vec::new(), Vec::new(), Err(InstructionError::NotEnoughAccountKeys), ); // Case: Not signed process_instruction( &loader_id, &[], &instruction_data, vec![(program_id, program_account.clone())], vec![AccountMeta { pubkey: program_id, is_signer: false, is_writable: false, }], Err(InstructionError::MissingRequiredSignature), ); // Case: Finalize let accounts = process_instruction( &loader_id, &[], &instruction_data, vec![(program_id, program_account.clone())], vec![AccountMeta { pubkey: program_id, is_signer: true, is_writable: false, }], Ok(()), ); assert!(accounts.first().unwrap().executable()); // Case: Finalize bad ELF *program_account.data_as_mut_slice().get_mut(0).unwrap() = 0; process_instruction( &loader_id, &[], &instruction_data, vec![(program_id, program_account)], vec![AccountMeta { pubkey: program_id, is_signer: true, is_writable: false, }], Err(InstructionError::InvalidAccountData), ); } #[test] fn test_bpf_loader_invoke_main() { let loader_id = bpf_loader::id(); let program_id = Pubkey::new_unique(); let mut program_account = load_program_account_from_elf(&loader_id, "test_elfs/noop_aligned.so"); let parameter_id = Pubkey::new_unique(); let parameter_account = AccountSharedData::new(1, 0, &loader_id); let parameter_meta = AccountMeta { pubkey: parameter_id, is_signer: false, is_writable: false, }; // Case: No program account process_instruction( &loader_id, &[], &[], Vec::new(), Vec::new(), Err(InstructionError::NotEnoughAccountKeys), ); // Case: Only a program account process_instruction( &loader_id, &[0], &[], vec![(program_id, program_account.clone())], Vec::new(), Ok(()), ); // Case: With program and parameter account process_instruction( &loader_id, &[0], &[], vec![ (program_id, program_account.clone()), (parameter_id, parameter_account.clone()), ], vec![parameter_meta.clone()], Ok(()), ); // Case: With duplicate accounts process_instruction( &loader_id, &[0], &[], vec![ (program_id, program_account.clone()), (parameter_id, parameter_account), ], vec![parameter_meta.clone(), parameter_meta], Ok(()), ); // Case: limited budget mock_process_instruction( &loader_id, vec![0], &[], vec![(program_id, program_account.clone())], Vec::new(), Err(InstructionError::ProgramFailedToComplete), |first_instruction_account: usize, instruction_data: &[u8], invoke_context: &mut InvokeContext| { invoke_context .get_compute_meter() .borrow_mut() .mock_set_remaining(0); super::process_instruction( first_instruction_account, instruction_data, invoke_context, ) }, ); // Case: Account not a program program_account.set_executable(false); process_instruction( &loader_id, &[0], &[], vec![(program_id, program_account)], Vec::new(), Err(InstructionError::IncorrectProgramId), ); } #[test] fn test_bpf_loader_serialize_unaligned() { let loader_id = bpf_loader_deprecated::id(); let program_id = Pubkey::new_unique(); let program_account = load_program_account_from_elf(&loader_id, "test_elfs/noop_unaligned.so"); let parameter_id = Pubkey::new_unique(); let parameter_account = AccountSharedData::new(1, 0, &loader_id); let parameter_meta = AccountMeta { pubkey: parameter_id, is_signer: false, is_writable: false, }; // Case: With program and parameter account process_instruction( &loader_id, &[0], &[], vec![ (program_id, program_account.clone()), (parameter_id, parameter_account.clone()), ], vec![parameter_meta.clone()], Ok(()), ); // Case: With duplicate accounts process_instruction( &loader_id, &[0], &[], vec![ (program_id, program_account), (parameter_id, parameter_account), ], vec![parameter_meta.clone(), parameter_meta], Ok(()), ); } #[test] fn test_bpf_loader_serialize_aligned() { let loader_id = bpf_loader::id(); let program_id = Pubkey::new_unique(); let program_account = load_program_account_from_elf(&loader_id, "test_elfs/noop_aligned.so"); let parameter_id = Pubkey::new_unique(); let parameter_account = AccountSharedData::new(1, 0, &loader_id); let parameter_meta = AccountMeta { pubkey: parameter_id, is_signer: false, is_writable: false, }; // Case: With program and parameter account process_instruction( &loader_id, &[0], &[], vec![ (program_id, program_account.clone()), (parameter_id, parameter_account.clone()), ], vec![parameter_meta.clone()], Ok(()), ); // Case: With duplicate accounts process_instruction( &loader_id, &[0], &[], vec![ (program_id, program_account), (parameter_id, parameter_account), ], vec![parameter_meta.clone(), parameter_meta], Ok(()), ); } #[test] fn test_bpf_loader_upgradeable_initialize_buffer() { let loader_id = bpf_loader_upgradeable::id(); let buffer_address = Pubkey::new_unique(); let buffer_account = AccountSharedData::new( 1, UpgradeableLoaderState::buffer_len(9).unwrap(), &loader_id, ); let authority_address = Pubkey::new_unique(); let authority_account = AccountSharedData::new( 1, UpgradeableLoaderState::buffer_len(9).unwrap(), &loader_id, ); let instruction_data = bincode::serialize(&UpgradeableLoaderInstruction::InitializeBuffer).unwrap(); let instruction_accounts = vec![ AccountMeta { pubkey: buffer_address, is_signer: false, is_writable: false, }, AccountMeta { pubkey: authority_address, is_signer: false, is_writable: false, }, ]; // Case: Success let accounts = process_instruction( &loader_id, &[], &instruction_data, vec![ (buffer_address, buffer_account), (authority_address, authority_account), ], instruction_accounts.clone(), Ok(()), ); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!( state, UpgradeableLoaderState::Buffer { authority_address: Some(authority_address) } ); // Case: Already initialized let accounts = process_instruction( &loader_id, &[], &instruction_data, vec![ (buffer_address, accounts.first().unwrap().clone()), (authority_address, accounts.get(1).unwrap().clone()), ], instruction_accounts, Err(InstructionError::AccountAlreadyInitialized), ); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!( state, UpgradeableLoaderState::Buffer { authority_address: Some(authority_address) } ); } #[test] fn test_bpf_loader_upgradeable_write() { let loader_id = bpf_loader_upgradeable::id(); let buffer_address = Pubkey::new_unique(); let mut buffer_account = AccountSharedData::new( 1, UpgradeableLoaderState::buffer_len(9).unwrap(), &loader_id, ); let instruction_accounts = vec![ AccountMeta { pubkey: buffer_address, is_signer: false, is_writable: false, }, AccountMeta { pubkey: buffer_address, is_signer: true, is_writable: false, }, ]; // Case: Not initialized let instruction = bincode::serialize(&UpgradeableLoaderInstruction::Write { offset: 0, bytes: vec![42; 9], }) .unwrap(); process_instruction( &loader_id, &[], &instruction, vec![(buffer_address, buffer_account.clone())], instruction_accounts.clone(), Err(InstructionError::InvalidAccountData), ); // Case: Write entire buffer let instruction = bincode::serialize(&UpgradeableLoaderInstruction::Write { offset: 0, bytes: vec![42; 9], }) .unwrap(); buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(buffer_address), }) .unwrap(); let accounts = process_instruction( &loader_id, &[], &instruction, vec![(buffer_address, buffer_account.clone())], instruction_accounts.clone(), Ok(()), ); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!( state, UpgradeableLoaderState::Buffer { authority_address: Some(buffer_address) } ); assert_eq!( &accounts .first() .unwrap() .data() .get(UpgradeableLoaderState::buffer_data_offset().unwrap()..) .unwrap(), &[42; 9] ); // Case: Write portion of the buffer let instruction = bincode::serialize(&UpgradeableLoaderInstruction::Write { offset: 3, bytes: vec![42; 6], }) .unwrap(); let mut buffer_account = AccountSharedData::new( 1, UpgradeableLoaderState::buffer_len(9).unwrap(), &loader_id, ); buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(buffer_address), }) .unwrap(); let accounts = process_instruction( &loader_id, &[], &instruction, vec![(buffer_address, buffer_account.clone())], instruction_accounts.clone(), Ok(()), ); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!( state, UpgradeableLoaderState::Buffer { authority_address: Some(buffer_address) } ); assert_eq!( &accounts .first() .unwrap() .data() .get(UpgradeableLoaderState::buffer_data_offset().unwrap()..) .unwrap(), &[0, 0, 0, 42, 42, 42, 42, 42, 42] ); // Case: overflow size let instruction = bincode::serialize(&UpgradeableLoaderInstruction::Write { offset: 0, bytes: vec![42; 10], }) .unwrap(); buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(buffer_address), }) .unwrap(); process_instruction( &loader_id, &[], &instruction, vec![(buffer_address, buffer_account.clone())], instruction_accounts.clone(), Err(InstructionError::AccountDataTooSmall), ); // Case: overflow offset let instruction = bincode::serialize(&UpgradeableLoaderInstruction::Write { offset: 1, bytes: vec![42; 9], }) .unwrap(); buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(buffer_address), }) .unwrap(); process_instruction( &loader_id, &[], &instruction, vec![(buffer_address, buffer_account.clone())], instruction_accounts.clone(), Err(InstructionError::AccountDataTooSmall), ); // Case: Not signed let instruction = bincode::serialize(&UpgradeableLoaderInstruction::Write { offset: 0, bytes: vec![42; 9], }) .unwrap(); buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(buffer_address), }) .unwrap(); process_instruction( &loader_id, &[], &instruction, vec![(buffer_address, buffer_account.clone())], vec![ AccountMeta { pubkey: buffer_address, is_signer: false, is_writable: false, }, AccountMeta { pubkey: buffer_address, is_signer: false, is_writable: false, }, ], Err(InstructionError::MissingRequiredSignature), ); // Case: wrong authority let authority_address = Pubkey::new_unique(); let instruction = bincode::serialize(&UpgradeableLoaderInstruction::Write { offset: 1, bytes: vec![42; 9], }) .unwrap(); buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(buffer_address), }) .unwrap(); process_instruction( &loader_id, &[], &instruction, vec![ (buffer_address, buffer_account.clone()), (authority_address, buffer_account.clone()), ], vec![ AccountMeta { pubkey: buffer_address, is_signer: false, is_writable: false, }, AccountMeta { pubkey: authority_address, is_signer: false, is_writable: false, }, ], Err(InstructionError::IncorrectAuthority), ); // Case: None authority let instruction = bincode::serialize(&UpgradeableLoaderInstruction::Write { offset: 1, bytes: vec![42; 9], }) .unwrap(); buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: None, }) .unwrap(); process_instruction( &loader_id, &[], &instruction, vec![(buffer_address, buffer_account.clone())], instruction_accounts, Err(InstructionError::Immutable), ); } fn truncate_data(account: &mut AccountSharedData, len: usize) { let mut data = account.data().to_vec(); data.truncate(len); account.set_data(data); } #[test] fn test_bpf_loader_upgradeable_deploy_with_max_len() { let (genesis_config, mint_keypair) = create_genesis_config(1_000_000_000); let mut bank = Bank::new_for_tests(&genesis_config); bank.feature_set = Arc::new(FeatureSet::all_enabled()); bank.add_builtin( "solana_bpf_loader_upgradeable_program", &bpf_loader_upgradeable::id(), super::process_instruction, ); let bank = Arc::new(bank); let bank_client = BankClient::new_shared(&bank); // Setup keypairs and addresses let payer_keypair = Keypair::new(); let program_keypair = Keypair::new(); let buffer_address = Pubkey::new_unique(); let (programdata_address, _) = Pubkey::find_program_address( &[program_keypair.pubkey().as_ref()], &bpf_loader_upgradeable::id(), ); let upgrade_authority_keypair = Keypair::new(); // Load program file let mut file = File::open("test_elfs/noop_aligned.so").expect("file open failed"); let mut elf = Vec::new(); file.read_to_end(&mut elf).unwrap(); // Compute rent exempt balances let program_len = elf.len(); let min_program_balance = bank .get_minimum_balance_for_rent_exemption(UpgradeableLoaderState::program_len().unwrap()); let min_buffer_balance = bank.get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::buffer_len(program_len).unwrap(), ); let min_programdata_balance = bank.get_minimum_balance_for_rent_exemption( UpgradeableLoaderState::programdata_len(program_len).unwrap(), ); // Setup accounts let buffer_account = { let mut account = AccountSharedData::new( min_buffer_balance, UpgradeableLoaderState::buffer_len(elf.len()).unwrap(), &bpf_loader_upgradeable::id(), ); account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(upgrade_authority_keypair.pubkey()), }) .unwrap(); account .data_as_mut_slice() .get_mut(UpgradeableLoaderState::buffer_data_offset().unwrap()..) .unwrap() .copy_from_slice(&elf); account }; let program_account = AccountSharedData::new( min_programdata_balance, UpgradeableLoaderState::program_len().unwrap(), &bpf_loader_upgradeable::id(), ); let programdata_account = AccountSharedData::new( 1, UpgradeableLoaderState::programdata_len(elf.len()).unwrap(), &bpf_loader_upgradeable::id(), ); // Test successful deploy let payer_base_balance = LAMPORTS_PER_SOL; let deploy_fees = { let fee_calculator = genesis_config.fee_rate_governor.create_fee_calculator(); 3 * fee_calculator.lamports_per_signature }; let min_payer_balance = min_program_balance .saturating_add(min_programdata_balance) .saturating_sub(min_buffer_balance.saturating_add(deploy_fees)); bank.store_account( &payer_keypair.pubkey(), &AccountSharedData::new( payer_base_balance.saturating_add(min_payer_balance), 0, &system_program::id(), ), ); bank.store_account(&buffer_address, &buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &payer_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(), Some(&payer_keypair.pubkey()), ); assert!(bank_client .send_and_confirm_message( &[&payer_keypair, &program_keypair, &upgrade_authority_keypair], message ) .is_ok()); assert_eq!( bank.get_balance(&payer_keypair.pubkey()), payer_base_balance ); assert_eq!(bank.get_balance(&buffer_address), 0); assert_eq!(None, bank.get_account(&buffer_address)); let post_program_account = bank.get_account(&program_keypair.pubkey()).unwrap(); assert_eq!(post_program_account.lamports(), min_program_balance); assert_eq!(post_program_account.owner(), &bpf_loader_upgradeable::id()); assert_eq!( post_program_account.data().len(), UpgradeableLoaderState::program_len().unwrap() ); let state: UpgradeableLoaderState = post_program_account.state().unwrap(); assert_eq!( state, UpgradeableLoaderState::Program { programdata_address } ); let post_programdata_account = bank.get_account(&programdata_address).unwrap(); assert_eq!(post_programdata_account.lamports(), min_programdata_balance); assert_eq!( post_programdata_account.owner(), &bpf_loader_upgradeable::id() ); let state: UpgradeableLoaderState = post_programdata_account.state().unwrap(); assert_eq!( state, UpgradeableLoaderState::ProgramData { slot: bank_client.get_slot().unwrap(), upgrade_authority_address: Some(upgrade_authority_keypair.pubkey()) } ); for (i, byte) in post_programdata_account .data() .get(UpgradeableLoaderState::programdata_data_offset().unwrap()..) .unwrap() .iter() .enumerate() { assert_eq!(*elf.get(i).unwrap(), *byte); } // Invoke deployed program process_instruction( &bpf_loader_upgradeable::id(), &[0, 1], &[], vec![ (programdata_address, post_programdata_account), (program_keypair.pubkey(), post_program_account), ], Vec::new(), Ok(()), ); // Test initialized program account bank.clear_signatures(); bank.store_account(&buffer_address, &buffer_account); let message = Message::new( &[Instruction::new_with_bincode( bpf_loader_upgradeable::id(), &UpgradeableLoaderInstruction::DeployWithMaxDataLen { max_data_len: elf.len(), }, vec![ AccountMeta::new(mint_keypair.pubkey(), true), AccountMeta::new(programdata_address, false), AccountMeta::new(program_keypair.pubkey(), false), AccountMeta::new(buffer_address, false), AccountMeta::new_readonly(sysvar::rent::id(), false), AccountMeta::new_readonly(sysvar::clock::id(), false), AccountMeta::new_readonly(system_program::id(), false), AccountMeta::new_readonly(upgrade_authority_keypair.pubkey(), true), ], )], Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(0, InstructionError::AccountAlreadyInitialized), bank_client .send_and_confirm_message(&[&mint_keypair, &upgrade_authority_keypair], message) .unwrap_err() .unwrap() ); // Test initialized ProgramData account bank.clear_signatures(); bank.store_account(&buffer_address, &buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(), Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(1, InstructionError::Custom(0)), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Test deploy no authority bank.clear_signatures(); bank.store_account(&buffer_address, &buffer_account); bank.store_account(&program_keypair.pubkey(), &program_account); bank.store_account(&programdata_address, &programdata_account); let message = Message::new( &[Instruction::new_with_bincode( bpf_loader_upgradeable::id(), &UpgradeableLoaderInstruction::DeployWithMaxDataLen { max_data_len: elf.len(), }, vec![ AccountMeta::new(mint_keypair.pubkey(), true), AccountMeta::new(programdata_address, false), AccountMeta::new(program_keypair.pubkey(), false), AccountMeta::new(buffer_address, false), AccountMeta::new_readonly(sysvar::rent::id(), false), AccountMeta::new_readonly(sysvar::clock::id(), false), AccountMeta::new_readonly(system_program::id(), false), ], )], Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(0, InstructionError::NotEnoughAccountKeys), bank_client .send_and_confirm_message(&[&mint_keypair], message) .unwrap_err() .unwrap() ); // Test deploy authority not a signer bank.clear_signatures(); bank.store_account(&buffer_address, &buffer_account); bank.store_account(&program_keypair.pubkey(), &program_account); bank.store_account(&programdata_address, &programdata_account); let message = Message::new( &[Instruction::new_with_bincode( bpf_loader_upgradeable::id(), &UpgradeableLoaderInstruction::DeployWithMaxDataLen { max_data_len: elf.len(), }, vec![ AccountMeta::new(mint_keypair.pubkey(), true), AccountMeta::new(programdata_address, false), AccountMeta::new(program_keypair.pubkey(), false), AccountMeta::new(buffer_address, false), AccountMeta::new_readonly(sysvar::rent::id(), false), AccountMeta::new_readonly(sysvar::clock::id(), false), AccountMeta::new_readonly(system_program::id(), false), AccountMeta::new_readonly(upgrade_authority_keypair.pubkey(), false), ], )], Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(0, InstructionError::MissingRequiredSignature), bank_client .send_and_confirm_message(&[&mint_keypair], message) .unwrap_err() .unwrap() ); // Test invalid Buffer account state bank.clear_signatures(); bank.store_account(&buffer_address, &AccountSharedData::default()); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(), Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(1, InstructionError::InvalidAccountData), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Test program account not rent exempt bank.clear_signatures(); bank.store_account(&buffer_address, &buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance.saturating_sub(1), elf.len(), ) .unwrap(), Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(1, InstructionError::ExecutableAccountNotRentExempt), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Test program account not rent exempt because data is larger than needed bank.clear_signatures(); bank.store_account(&buffer_address, &buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let mut instructions = bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(); *instructions.get_mut(0).unwrap() = system_instruction::create_account( &mint_keypair.pubkey(), &program_keypair.pubkey(), min_program_balance, (UpgradeableLoaderState::program_len().unwrap() as u64).saturating_add(1), &id(), ); let message = Message::new(&instructions, Some(&mint_keypair.pubkey())); assert_eq!( TransactionError::InstructionError(1, InstructionError::ExecutableAccountNotRentExempt), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Test program account too small bank.clear_signatures(); bank.store_account(&buffer_address, &buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let mut instructions = bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(); *instructions.get_mut(0).unwrap() = system_instruction::create_account( &mint_keypair.pubkey(), &program_keypair.pubkey(), min_program_balance, (UpgradeableLoaderState::program_len().unwrap() as u64).saturating_sub(1), &id(), ); let message = Message::new(&instructions, Some(&mint_keypair.pubkey())); assert_eq!( TransactionError::InstructionError(1, InstructionError::AccountDataTooSmall), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Test Insufficient payer funds (need more funds to cover the // difference between buffer lamports and programdata lamports) bank.clear_signatures(); bank.store_account( &mint_keypair.pubkey(), &AccountSharedData::new( deploy_fees.saturating_add(min_program_balance), 0, &system_program::id(), ), ); bank.store_account(&buffer_address, &buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(), Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(1, InstructionError::Custom(1)), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); bank.store_account( &mint_keypair.pubkey(), &AccountSharedData::new(1_000_000_000, 0, &system_program::id()), ); // Test max_data_len bank.clear_signatures(); bank.store_account(&buffer_address, &buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len().saturating_sub(1), ) .unwrap(), Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(1, InstructionError::AccountDataTooSmall), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Test max_data_len too large bank.clear_signatures(); bank.store_account( &mint_keypair.pubkey(), &AccountSharedData::new(u64::MAX / 2, 0, &system_program::id()), ); let mut modified_buffer_account = buffer_account.clone(); modified_buffer_account.set_lamports(u64::MAX / 2); bank.store_account(&buffer_address, &modified_buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, usize::MAX, ) .unwrap(), Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(1, InstructionError::InvalidArgument), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Test not the system account bank.clear_signatures(); bank.store_account(&buffer_address, &buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let mut instructions = bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(); *instructions .get_mut(1) .unwrap() .accounts .get_mut(6) .unwrap() = AccountMeta::new_readonly(Pubkey::new_unique(), false); let message = Message::new(&instructions, Some(&mint_keypair.pubkey())); assert_eq!( TransactionError::InstructionError(1, InstructionError::MissingAccount), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Test Bad ELF data bank.clear_signatures(); let mut modified_buffer_account = buffer_account; truncate_data( &mut modified_buffer_account, UpgradeableLoaderState::buffer_len(1).unwrap(), ); bank.store_account(&buffer_address, &modified_buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(), Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(1, InstructionError::InvalidAccountData), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Test small buffer account bank.clear_signatures(); let mut modified_buffer_account = AccountSharedData::new( min_programdata_balance, UpgradeableLoaderState::buffer_len(elf.len()).unwrap(), &bpf_loader_upgradeable::id(), ); modified_buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(upgrade_authority_keypair.pubkey()), }) .unwrap(); modified_buffer_account .data_as_mut_slice() .get_mut(UpgradeableLoaderState::buffer_data_offset().unwrap()..) .unwrap() .copy_from_slice(&elf); truncate_data(&mut modified_buffer_account, 5); bank.store_account(&buffer_address, &modified_buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(), Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(1, InstructionError::InvalidAccountData), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Mismatched buffer and program authority bank.clear_signatures(); let mut modified_buffer_account = AccountSharedData::new( min_programdata_balance, UpgradeableLoaderState::buffer_len(elf.len()).unwrap(), &bpf_loader_upgradeable::id(), ); modified_buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(buffer_address), }) .unwrap(); modified_buffer_account .data_as_mut_slice() .get_mut(UpgradeableLoaderState::buffer_data_offset().unwrap()..) .unwrap() .copy_from_slice(&elf); bank.store_account(&buffer_address, &modified_buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(), Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(1, InstructionError::IncorrectAuthority), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); // Deploy buffer with mismatched None authority bank.clear_signatures(); let mut modified_buffer_account = AccountSharedData::new( min_programdata_balance, UpgradeableLoaderState::buffer_len(elf.len()).unwrap(), &bpf_loader_upgradeable::id(), ); modified_buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: None, }) .unwrap(); modified_buffer_account .data_as_mut_slice() .get_mut(UpgradeableLoaderState::buffer_data_offset().unwrap()..) .unwrap() .copy_from_slice(&elf); bank.store_account(&buffer_address, &modified_buffer_account); bank.store_account(&program_keypair.pubkey(), &AccountSharedData::default()); bank.store_account(&programdata_address, &AccountSharedData::default()); let message = Message::new( &bpf_loader_upgradeable::deploy_with_max_program_len( &mint_keypair.pubkey(), &program_keypair.pubkey(), &buffer_address, &upgrade_authority_keypair.pubkey(), min_program_balance, elf.len(), ) .unwrap(), Some(&mint_keypair.pubkey()), ); assert_eq!( TransactionError::InstructionError(1, InstructionError::IncorrectAuthority), bank_client .send_and_confirm_message( &[&mint_keypair, &program_keypair, &upgrade_authority_keypair], message ) .unwrap_err() .unwrap() ); } #[test] fn test_bpf_loader_upgradeable_upgrade() { let mut file = File::open("test_elfs/noop_aligned.so").expect("file open failed"); let mut elf_orig = Vec::new(); file.read_to_end(&mut elf_orig).unwrap(); let mut file = File::open("test_elfs/noop_unaligned.so").expect("file open failed"); let mut elf_new = Vec::new(); file.read_to_end(&mut elf_new).unwrap(); assert_ne!(elf_orig.len(), elf_new.len()); const SLOT: u64 = 42; let buffer_address = Pubkey::new_unique(); let upgrade_authority_address = Pubkey::new_unique(); fn get_accounts( buffer_address: &Pubkey, buffer_authority: &Pubkey, upgrade_authority_address: &Pubkey, elf_orig: &[u8], elf_new: &[u8], ) -> (Vec<(Pubkey, AccountSharedData)>, Vec<AccountMeta>) { let loader_id = bpf_loader_upgradeable::id(); let program_address = Pubkey::new_unique(); let spill_address = Pubkey::new_unique(); let rent = Rent::default(); let min_program_balance = 1.max(rent.minimum_balance(UpgradeableLoaderState::program_len().unwrap())); let min_programdata_balance = 1.max(rent.minimum_balance( UpgradeableLoaderState::programdata_len(elf_orig.len().max(elf_new.len())).unwrap(), )); let (programdata_address, _) = Pubkey::find_program_address(&[program_address.as_ref()], &loader_id); let mut buffer_account = AccountSharedData::new( 1, UpgradeableLoaderState::buffer_len(elf_new.len()).unwrap(), &bpf_loader_upgradeable::id(), ); buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(*buffer_authority), }) .unwrap(); buffer_account .data_as_mut_slice() .get_mut(UpgradeableLoaderState::buffer_data_offset().unwrap()..) .unwrap() .copy_from_slice(elf_new); let mut programdata_account = AccountSharedData::new( min_programdata_balance, UpgradeableLoaderState::programdata_len(elf_orig.len().max(elf_new.len())).unwrap(), &bpf_loader_upgradeable::id(), ); programdata_account .set_state(&UpgradeableLoaderState::ProgramData { slot: SLOT, upgrade_authority_address: Some(*upgrade_authority_address), }) .unwrap(); let mut program_account = AccountSharedData::new( min_program_balance, UpgradeableLoaderState::program_len().unwrap(), &bpf_loader_upgradeable::id(), ); program_account.set_executable(true); program_account .set_state(&UpgradeableLoaderState::Program { programdata_address, }) .unwrap(); let spill_account = AccountSharedData::new(0, 0, &Pubkey::new_unique()); let rent_account = create_account_for_test(&rent); let clock_account = create_account_for_test(&Clock { slot: SLOT, ..Clock::default() }); let upgrade_authority_account = AccountSharedData::new(1, 0, &Pubkey::new_unique()); let transaction_accounts = vec![ (programdata_address, programdata_account), (program_address, program_account), (*buffer_address, buffer_account), (spill_address, spill_account), (sysvar::rent::id(), rent_account), (sysvar::clock::id(), clock_account), (*upgrade_authority_address, upgrade_authority_account), ]; let instruction_accounts = vec![ AccountMeta { pubkey: programdata_address, is_signer: false, is_writable: true, }, AccountMeta { pubkey: program_address, is_signer: false, is_writable: true, }, AccountMeta { pubkey: *buffer_address, is_signer: false, is_writable: true, }, AccountMeta { pubkey: spill_address, is_signer: false, is_writable: true, }, AccountMeta { pubkey: sysvar::rent::id(), is_signer: false, is_writable: false, }, AccountMeta { pubkey: sysvar::clock::id(), is_signer: false, is_writable: false, }, AccountMeta { pubkey: *upgrade_authority_address, is_signer: true, is_writable: false, }, ]; (transaction_accounts, instruction_accounts) } fn process_instruction( transaction_accounts: Vec<(Pubkey, AccountSharedData)>, instruction_accounts: Vec<AccountMeta>, expected_result: Result<(), InstructionError>, ) -> Vec<AccountSharedData> { let instruction_data = bincode::serialize(&UpgradeableLoaderInstruction::Upgrade).unwrap(); mock_process_instruction( &bpf_loader_upgradeable::id(), Vec::new(), &instruction_data, transaction_accounts, instruction_accounts, expected_result, super::process_instruction, ) } // Case: Success let (transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); let accounts = process_instruction(transaction_accounts, instruction_accounts, Ok(())); let min_programdata_balance = Rent::default().minimum_balance( UpgradeableLoaderState::programdata_len(elf_orig.len().max(elf_new.len())).unwrap(), ); assert_eq!( min_programdata_balance, accounts.first().unwrap().lamports() ); assert_eq!(0, accounts.get(2).unwrap().lamports()); assert_eq!(1, accounts.get(3).unwrap().lamports()); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!( state, UpgradeableLoaderState::ProgramData { slot: SLOT, upgrade_authority_address: Some(upgrade_authority_address) } ); for (i, byte) in accounts .first() .unwrap() .data() .get( UpgradeableLoaderState::programdata_data_offset().unwrap() ..UpgradeableLoaderState::programdata_data_offset() .unwrap() .saturating_add(elf_new.len()), ) .unwrap() .iter() .enumerate() { assert_eq!(*elf_new.get(i).unwrap(), *byte); } // Case: not upgradable let (mut transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); transaction_accounts .get_mut(0) .unwrap() .1 .set_state(&UpgradeableLoaderState::ProgramData { slot: SLOT, upgrade_authority_address: None, }) .unwrap(); process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::Immutable), ); // Case: wrong authority let (mut transaction_accounts, mut instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); let invalid_upgrade_authority_address = Pubkey::new_unique(); transaction_accounts.get_mut(6).unwrap().0 = invalid_upgrade_authority_address; instruction_accounts.get_mut(6).unwrap().pubkey = invalid_upgrade_authority_address; process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::IncorrectAuthority), ); // Case: authority did not sign let (transaction_accounts, mut instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); instruction_accounts.get_mut(6).unwrap().is_signer = false; process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::MissingRequiredSignature), ); // Case: Program account not executable let (mut transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); transaction_accounts .get_mut(1) .unwrap() .1 .set_executable(false); process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::AccountNotExecutable), ); // Case: Program account now owned by loader let (mut transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); transaction_accounts .get_mut(1) .unwrap() .1 .set_owner(Pubkey::new_unique()); process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::IncorrectProgramId), ); // Case: Program account not writable let (transaction_accounts, mut instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); instruction_accounts.get_mut(1).unwrap().is_writable = false; process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::InvalidArgument), ); // Case: Program account not initialized let (mut transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); transaction_accounts .get_mut(1) .unwrap() .1 .set_state(&UpgradeableLoaderState::Uninitialized) .unwrap(); process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::InvalidAccountData), ); // Case: Program ProgramData account mismatch let (mut transaction_accounts, mut instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); let invalid_programdata_address = Pubkey::new_unique(); transaction_accounts.get_mut(0).unwrap().0 = invalid_programdata_address; instruction_accounts.get_mut(0).unwrap().pubkey = invalid_programdata_address; process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::InvalidArgument), ); // Case: Buffer account not initialized let (mut transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); transaction_accounts .get_mut(2) .unwrap() .1 .set_state(&UpgradeableLoaderState::Uninitialized) .unwrap(); process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::InvalidArgument), ); // Case: Buffer account too big let (mut transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); transaction_accounts.get_mut(2).unwrap().1 = AccountSharedData::new( 1, UpgradeableLoaderState::buffer_len(elf_orig.len().max(elf_new.len()).saturating_add(1)) .unwrap(), &bpf_loader_upgradeable::id(), ); transaction_accounts .get_mut(2) .unwrap() .1 .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(upgrade_authority_address), }) .unwrap(); process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::AccountDataTooSmall), ); // Test small buffer account let (mut transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &upgrade_authority_address, &upgrade_authority_address, &elf_orig, &elf_new, ); transaction_accounts .get_mut(2) .unwrap() .1 .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(upgrade_authority_address), }) .unwrap(); truncate_data(&mut transaction_accounts.get_mut(2).unwrap().1, 5); process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::InvalidAccountData), ); // Case: Mismatched buffer and program authority let (transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &buffer_address, &upgrade_authority_address, &elf_orig, &elf_new, ); process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::IncorrectAuthority), ); // Case: None buffer authority let (mut transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &buffer_address, &upgrade_authority_address, &elf_orig, &elf_new, ); transaction_accounts .get_mut(2) .unwrap() .1 .set_state(&UpgradeableLoaderState::Buffer { authority_address: None, }) .unwrap(); process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::IncorrectAuthority), ); // Case: None buffer and program authority let (mut transaction_accounts, instruction_accounts) = get_accounts( &buffer_address, &buffer_address, &upgrade_authority_address, &elf_orig, &elf_new, ); transaction_accounts .get_mut(0) .unwrap() .1 .set_state(&UpgradeableLoaderState::ProgramData { slot: SLOT, upgrade_authority_address: None, }) .unwrap(); transaction_accounts .get_mut(2) .unwrap() .1 .set_state(&UpgradeableLoaderState::Buffer { authority_address: None, }) .unwrap(); process_instruction( transaction_accounts, instruction_accounts, Err(InstructionError::IncorrectAuthority), ); } #[test] fn test_bpf_loader_upgradeable_set_upgrade_authority() { let instruction = bincode::serialize(&UpgradeableLoaderInstruction::SetAuthority).unwrap(); let loader_id = bpf_loader_upgradeable::id(); let slot = 0; let upgrade_authority_address = Pubkey::new_unique(); let upgrade_authority_account = AccountSharedData::new(1, 0, &Pubkey::new_unique()); let new_upgrade_authority_address = Pubkey::new_unique(); let new_upgrade_authority_account = AccountSharedData::new(1, 0, &Pubkey::new_unique()); let program_address = Pubkey::new_unique(); let (programdata_address, _) = Pubkey::find_program_address( &[program_address.as_ref()], &bpf_loader_upgradeable::id(), ); let mut programdata_account = AccountSharedData::new( 1, UpgradeableLoaderState::programdata_len(0).unwrap(), &bpf_loader_upgradeable::id(), ); programdata_account .set_state(&UpgradeableLoaderState::ProgramData { slot, upgrade_authority_address: Some(upgrade_authority_address), }) .unwrap(); let programdata_meta = AccountMeta { pubkey: programdata_address, is_signer: false, is_writable: false, }; let upgrade_authority_meta = AccountMeta { pubkey: upgrade_authority_address, is_signer: true, is_writable: false, }; let new_upgrade_authority_meta = AccountMeta { pubkey: new_upgrade_authority_address, is_signer: false, is_writable: false, }; // Case: Set to new authority let accounts = process_instruction( &loader_id, &[], &instruction, vec![ (programdata_address, programdata_account.clone()), (upgrade_authority_address, upgrade_authority_account.clone()), ( new_upgrade_authority_address, new_upgrade_authority_account.clone(), ), ], vec![ programdata_meta.clone(), upgrade_authority_meta.clone(), new_upgrade_authority_meta.clone(), ], Ok(()), ); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!( state, UpgradeableLoaderState::ProgramData { slot, upgrade_authority_address: Some(new_upgrade_authority_address), } ); // Case: Not upgradeable let accounts = process_instruction( &loader_id, &[], &instruction, vec![ (programdata_address, programdata_account.clone()), (upgrade_authority_address, upgrade_authority_account.clone()), ], vec![programdata_meta.clone(), upgrade_authority_meta.clone()], Ok(()), ); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!( state, UpgradeableLoaderState::ProgramData { slot, upgrade_authority_address: None, } ); // Case: Authority did not sign process_instruction( &loader_id, &[], &instruction, vec![ (programdata_address, programdata_account.clone()), (upgrade_authority_address, upgrade_authority_account.clone()), ], vec![ programdata_meta.clone(), AccountMeta { pubkey: upgrade_authority_address, is_signer: false, is_writable: false, }, ], Err(InstructionError::MissingRequiredSignature), ); // Case: wrong authority let invalid_upgrade_authority_address = Pubkey::new_unique(); process_instruction( &loader_id, &[], &instruction, vec![ (programdata_address, programdata_account.clone()), ( invalid_upgrade_authority_address, upgrade_authority_account.clone(), ), (new_upgrade_authority_address, new_upgrade_authority_account), ], vec![ programdata_meta.clone(), AccountMeta { pubkey: invalid_upgrade_authority_address, is_signer: true, is_writable: false, }, new_upgrade_authority_meta, ], Err(InstructionError::IncorrectAuthority), ); // Case: No authority programdata_account .set_state(&UpgradeableLoaderState::ProgramData { slot, upgrade_authority_address: None, }) .unwrap(); process_instruction( &loader_id, &[], &instruction, vec![ (programdata_address, programdata_account.clone()), (upgrade_authority_address, upgrade_authority_account.clone()), ], vec![programdata_meta.clone(), upgrade_authority_meta.clone()], Err(InstructionError::Immutable), ); // Case: Not a ProgramData account programdata_account .set_state(&UpgradeableLoaderState::Program { programdata_address: Pubkey::new_unique(), }) .unwrap(); process_instruction( &loader_id, &[], &instruction, vec![ (programdata_address, programdata_account.clone()), (upgrade_authority_address, upgrade_authority_account), ], vec![programdata_meta, upgrade_authority_meta], Err(InstructionError::InvalidArgument), ); } #[test] fn test_bpf_loader_upgradeable_set_buffer_authority() { let instruction = bincode::serialize(&UpgradeableLoaderInstruction::SetAuthority).unwrap(); let loader_id = bpf_loader_upgradeable::id(); let invalid_authority_address = Pubkey::new_unique(); let authority_address = Pubkey::new_unique(); let authority_account = AccountSharedData::new(1, 0, &Pubkey::new_unique()); let new_authority_address = Pubkey::new_unique(); let new_authority_account = AccountSharedData::new(1, 0, &Pubkey::new_unique()); let buffer_address = Pubkey::new_unique(); let mut buffer_account = AccountSharedData::new( 1, UpgradeableLoaderState::buffer_len(0).unwrap(), &loader_id, ); buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(authority_address), }) .unwrap(); let mut transaction_accounts = vec![ (buffer_address, buffer_account.clone()), (authority_address, authority_account.clone()), (new_authority_address, new_authority_account.clone()), ]; let buffer_meta = AccountMeta { pubkey: buffer_address, is_signer: false, is_writable: false, }; let authority_meta = AccountMeta { pubkey: authority_address, is_signer: true, is_writable: false, }; let new_authority_meta = AccountMeta { pubkey: new_authority_address, is_signer: false, is_writable: false, }; // Case: New authority required let accounts = process_instruction( &loader_id, &[], &instruction, transaction_accounts.clone(), vec![buffer_meta.clone(), authority_meta.clone()], Err(InstructionError::IncorrectAuthority), ); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!( state, UpgradeableLoaderState::Buffer { authority_address: Some(authority_address), } ); // Case: Set to new authority buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(authority_address), }) .unwrap(); let accounts = process_instruction( &loader_id, &[], &instruction, transaction_accounts.clone(), vec![ buffer_meta.clone(), authority_meta.clone(), new_authority_meta.clone(), ], Ok(()), ); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!( state, UpgradeableLoaderState::Buffer { authority_address: Some(new_authority_address), } ); // Case: Authority did not sign process_instruction( &loader_id, &[], &instruction, transaction_accounts.clone(), vec![ buffer_meta.clone(), AccountMeta { pubkey: authority_address, is_signer: false, is_writable: false, }, new_authority_meta.clone(), ], Err(InstructionError::MissingRequiredSignature), ); // Case: wrong authority process_instruction( &loader_id, &[], &instruction, vec![ (buffer_address, buffer_account.clone()), (invalid_authority_address, authority_account), (new_authority_address, new_authority_account), ], vec![ buffer_meta.clone(), AccountMeta { pubkey: invalid_authority_address, is_signer: true, is_writable: false, }, new_authority_meta.clone(), ], Err(InstructionError::IncorrectAuthority), ); // Case: No authority process_instruction( &loader_id, &[], &instruction, transaction_accounts.clone(), vec![buffer_meta.clone(), authority_meta.clone()], Err(InstructionError::IncorrectAuthority), ); // Case: Set to no authority transaction_accounts .get_mut(0) .unwrap() .1 .set_state(&UpgradeableLoaderState::Buffer { authority_address: None, }) .unwrap(); process_instruction( &loader_id, &[], &instruction, transaction_accounts.clone(), vec![ buffer_meta.clone(), authority_meta.clone(), new_authority_meta.clone(), ], Err(InstructionError::Immutable), ); // Case: Not a Buffer account transaction_accounts .get_mut(0) .unwrap() .1 .set_state(&UpgradeableLoaderState::Program { programdata_address: Pubkey::new_unique(), }) .unwrap(); process_instruction( &loader_id, &[], &instruction, transaction_accounts.clone(), vec![buffer_meta, authority_meta, new_authority_meta], Err(InstructionError::InvalidArgument), ); } #[test] fn test_bpf_loader_upgradeable_close() { let instruction = bincode::serialize(&UpgradeableLoaderInstruction::Close).unwrap(); let loader_id = bpf_loader_upgradeable::id(); let invalid_authority_address = Pubkey::new_unique(); let authority_address = Pubkey::new_unique(); let authority_account = AccountSharedData::new(1, 0, &Pubkey::new_unique()); let recipient_address = Pubkey::new_unique(); let recipient_account = AccountSharedData::new(1, 0, &Pubkey::new_unique()); let buffer_address = Pubkey::new_unique(); let mut buffer_account = AccountSharedData::new( 1, UpgradeableLoaderState::buffer_len(0).unwrap(), &loader_id, ); buffer_account .set_state(&UpgradeableLoaderState::Buffer { authority_address: Some(authority_address), }) .unwrap(); let uninitialized_address = Pubkey::new_unique(); let mut uninitialized_account = AccountSharedData::new( 1, UpgradeableLoaderState::programdata_len(0).unwrap(), &loader_id, ); uninitialized_account .set_state(&UpgradeableLoaderState::Uninitialized) .unwrap(); let programdata_address = Pubkey::new_unique(); let mut programdata_account = AccountSharedData::new( 1, UpgradeableLoaderState::programdata_len(0).unwrap(), &loader_id, ); programdata_account .set_state(&UpgradeableLoaderState::ProgramData { slot: 0, upgrade_authority_address: Some(authority_address), }) .unwrap(); let program_address = Pubkey::new_unique(); let mut program_account = AccountSharedData::new( 1, UpgradeableLoaderState::program_len().unwrap(), &loader_id, ); program_account.set_executable(true); program_account .set_state(&UpgradeableLoaderState::Program { programdata_address, }) .unwrap(); let transaction_accounts = vec![ (buffer_address, buffer_account.clone()), (recipient_address, recipient_account.clone()), (authority_address, authority_account.clone()), ]; let buffer_meta = AccountMeta { pubkey: buffer_address, is_signer: false, is_writable: false, }; let recipient_meta = AccountMeta { pubkey: recipient_address, is_signer: false, is_writable: false, }; let authority_meta = AccountMeta { pubkey: authority_address, is_signer: true, is_writable: false, }; // Case: close a buffer account let accounts = process_instruction( &loader_id, &[], &instruction, transaction_accounts, vec![ buffer_meta.clone(), recipient_meta.clone(), authority_meta.clone(), ], Ok(()), ); assert_eq!(0, accounts.first().unwrap().lamports()); assert_eq!(2, accounts.get(1).unwrap().lamports()); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!(state, UpgradeableLoaderState::Uninitialized); // Case: close with wrong authority process_instruction( &loader_id, &[], &instruction, vec![ (buffer_address, buffer_account.clone()), (recipient_address, recipient_account.clone()), (invalid_authority_address, authority_account.clone()), ], vec![ buffer_meta, recipient_meta.clone(), AccountMeta { pubkey: invalid_authority_address, is_signer: true, is_writable: false, }, ], Err(InstructionError::IncorrectAuthority), ); // Case: close an uninitialized account let accounts = process_instruction( &loader_id, &[], &instruction, vec![ (uninitialized_address, uninitialized_account.clone()), (recipient_address, recipient_account.clone()), (invalid_authority_address, authority_account.clone()), ], vec![ AccountMeta { pubkey: uninitialized_address, is_signer: false, is_writable: false, }, recipient_meta.clone(), authority_meta.clone(), ], Ok(()), ); assert_eq!(0, accounts.first().unwrap().lamports()); assert_eq!(2, accounts.get(1).unwrap().lamports()); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!(state, UpgradeableLoaderState::Uninitialized); // Case: close a program account let accounts = process_instruction( &loader_id, &[], &instruction, vec![ (programdata_address, programdata_account.clone()), (recipient_address, recipient_account), (authority_address, authority_account), (program_address, program_account.clone()), ], vec![ AccountMeta { pubkey: programdata_address, is_signer: false, is_writable: false, }, recipient_meta, authority_meta, AccountMeta { pubkey: program_address, is_signer: false, is_writable: true, }, ], Ok(()), ); assert_eq!(0, accounts.first().unwrap().lamports()); assert_eq!(2, accounts.get(1).unwrap().lamports()); let state: UpgradeableLoaderState = accounts.first().unwrap().state().unwrap(); assert_eq!(state, UpgradeableLoaderState::Uninitialized); // Try to invoke closed account process_instruction( &program_address, &[0, 1], &[], vec![ (programdata_address, programdata_account.clone()), (program_address, program_account.clone()), ], Vec::new(), Err(InstructionError::InvalidAccountData), ); } /// fuzzing utility function fn fuzz<F>( bytes: &[u8], outer_iters: usize, inner_iters: usize, offset: Range<usize>, value: Range<u8>, work: F, ) where F: Fn(&mut [u8]), { let mut rng = rand::thread_rng(); for _ in 0..outer_iters { let mut mangled_bytes = bytes.to_vec(); for _ in 0..inner_iters { let offset = rng.gen_range(offset.start, offset.end); let value = rng.gen_range(value.start, value.end); *mangled_bytes.get_mut(offset).unwrap() = value; work(&mut mangled_bytes); } } } #[test] #[ignore] fn test_fuzz() { let loader_id = bpf_loader::id(); let program_id = Pubkey::new_unique(); // Create program account let mut file = File::open("test_elfs/noop_aligned.so").expect("file open failed"); let mut elf = Vec::new(); file.read_to_end(&mut elf).unwrap(); // Mangle the whole file fuzz( &elf, 1_000_000_000, 100, 0..elf.len(), 0..255, |bytes: &mut [u8]| { let mut program_account = AccountSharedData::new(1, 0, &loader_id); program_account.set_data(bytes.to_vec()); program_account.set_executable(true); process_instruction( &loader_id, &[], &[], vec![(program_id, program_account)], Vec::new(), Ok(()), ); }, ); } }
{ self.compute_meter.borrow().get_remaining() }
parseModuleExport.ts
import fs from 'fs'; import path from 'path'; import glob from 'glob'; import parseEsImport from 'parse-es-import'; type ModuleExportInfo = { /** Module name */ name; /** Path of module's source file */ moduleFilePath: string; /** Source code of module */ rawCode: string; }; export type ModuleExportMap = { [key: string]: Array<ModuleExportInfo>; }; /** * Parse exported modules of file */ export default function parseModuleExport({ statsModules, context, validPaths, fileDependencyMap, needRawCode, }: { statsModules: Array<{ [key: string]: any }>; context: string; validPaths: string[]; fileDependencyMap: { [key: string]: string[] }; needRawCode: boolean; }): ModuleExportMap { const result: ModuleExportMap = {}; if (!Object.keys(fileDependencyMap).length) { return result;
} for (const { name, source } of statsModules) { const pathCurrent = path.resolve(context, name); const dirPathCurrent = path.dirname(pathCurrent); if (validPaths.indexOf(pathCurrent) === -1) { continue; } const moduleInfoList: ModuleExportInfo[] = []; const { imports, exports } = parseEsImport(source); for (const { type, moduleName, value } of exports) { switch (type) { case 'ExportSpecifier': const [pathImport] = glob.sync( path.resolve(dirPathCurrent, `${value}?(.jsx|.js|.ts|.tsx)`) ); if (pathImport) { moduleInfoList.push({ name: moduleName, rawCode: needRawCode ? fs.readFileSync(pathImport, 'utf8') : '', moduleFilePath: pathImport, }); } break; case 'FunctionDeclaration': case 'VariableDeclaration': // Coupled with the content of the file, the content that needs to be parsed is as follows // import * as _DOC from 'xxx.md'; // export const DOC = _DOC; let moduleFilePath = ''; let rawCode = needRawCode ? value : ''; for (const { starImport, defaultImport, moduleName: importModuleName } of imports) { if ( moduleName === starImport.replace(/^_/, '') || moduleName === defaultImport.replace(/^_/, '') ) { const [pathImport] = glob.sync( path.resolve(dirPathCurrent, `${importModuleName}?(.jsx|.js|.ts|.tsx)`) ); if (pathImport) { moduleFilePath = pathImport; rawCode = needRawCode ? fs.readFileSync(pathImport, 'utf8') : ''; } break; } } moduleInfoList.push({ name: moduleName, rawCode, moduleFilePath, }); break; default: break; } } result[pathCurrent] = moduleInfoList; } return result; }
state.js
const Promise = require('bluebird'); const Errors = require('common-errors'); const moment = require('moment'); const { ActionTransport } = require('@microfleet/core'); // helpers const key = require('../../redis-key'); const { agreement: operations } = require('../../utils/paypal'); const resetToFreePlan = require('../../utils/reset-to-free-plan'); const { serialize } = require('../../utils/redis'); const { AGREEMENT_DATA, FREE_PLAN_ID } = require('../../constants'); // correctly save state const ACTION_TO_STATE = { suspend: 'suspended', reactivate: 'active', cancel: 'cancelled', }; const isErrorToBeIgnored = (err) => { return err.httpStatusCode === 400 && err.response && err.response.name === 'STATUS_INVALID' && err.response.message === 'Invalid profile status for cancel action; profile should be active or suspended'; }; /** * @api {amqp} <prefix>.agreement.state Changes agreement state * @apiVersion 1.0.0 * @apiName agreementState * @apiGroup Agreement * * @apiDescription Change currently used agreement for {owner} to {state} * * @apiParam (Params) {Object} params - request container * @apiParam (Params) {String} params.owner - user to change agreement state for * @apiParam (Params) {String="suspend","reactivate","cancel"} params.state - new state */ async function
({ params: message }) { const { config, redis, amqp, log } = this; const { users: { prefix, postfix, audience } } = config; const { owner, state } = message; const note = message.note || `Applying '${state}' operation to agreement`; const getIdPath = `${prefix}.${postfix.getMetadata}`; const getIdRequest = { username: owner, audience }; const meta = await amqp .publishAndWait(getIdPath, getIdRequest, { timeout: 5000 }) .get(audience); const { agreement: id, subscriptionInterval, subscriptionType } = meta; const agreementKey = key(AGREEMENT_DATA, id); if (id === FREE_PLAN_ID) { throw new Errors.NotPermittedError('User has free plan/agreement'); } if (subscriptionType === 'capp') { throw new Errors.NotPermittedError('Must use capp payments service'); } try { log.info({ state, agreementId: id, note }, 'updating agreement state'); await operations[state].call(this, id, { note }, config.paypal); } catch (err) { if (!isErrorToBeIgnored(err)) { log.error({ err, state, agreementId: id, note }, 'failed to update agreement state'); throw new Errors.HttpStatusError(err.httpStatusCode, `[${state}] ${id}: ${err.response.message}`, err.response.name); } else { log.warn({ err, state, agreementId: id, note }, 'failed to update agreement state, but can be ignored'); } } await this.dispatch('transaction.sync', { params: { id, owner, start: moment().subtract(2, subscriptionInterval).format('YYYY-MM-DD'), end: moment().add(1, 'day').format('YYYY-MM-DD'), }, }); const promises = [ redis.hmset(agreementKey, serialize({ state: ACTION_TO_STATE[state] })), ]; if (state === 'cancel') { promises.push(resetToFreePlan.call(this, owner)); } await Promise.all(promises); return state; } agreementState.transports = [ActionTransport.amqp, ActionTransport.internal]; module.exports = agreementState;
agreementState
cyclonedx_valid_test.go
package cli import ( "os" "strings" "testing" "github.com/anchore/stereoscope/pkg/imagetest" ) // We have schema validation mechanims in schema/cyclonedx/ // This test allows us to double check that validation against the cyclonedx-cli tool func TestValidCycloneDX(t *testing.T) { imageFixture := func(t *testing.T) string { fixtureImageName := "image-pkg-coverage" imagetest.GetFixtureImage(t, "docker-archive", fixtureImageName) tarPath := imagetest.GetFixtureImageTarPath(t, fixtureImageName) return "docker-archive:" + tarPath } // TODO update image to exercise entire cyclonedx schema tests := []struct { name string subcommand string args []string fixture func(*testing.T) string assertions []traitAssertion }{ { name: "validate cyclonedx output", subcommand: "packages", args: []string{"-o", "cyclonedx-json"}, fixture: imageFixture, assertions: []traitAssertion{ assertSuccessfulReturnCode, assertValidCycloneDX, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { fixtureRef := test.fixture(t) args := []string{ test.subcommand, fixtureRef, "-q", } for _, a := range test.args { args = append(args, a) } cmd, stdout, stderr := runSyft(t, nil, args...) for _, traitFn := range test.assertions { traitFn(t, stdout, stderr, cmd.ProcessState.ExitCode()) } if t.Failed() { t.Log("STDOUT:\n", stdout) t.Log("STDERR:\n", stderr) t.Log("COMMAND:", strings.Join(cmd.Args, " ")) } validateCycloneDXJSON(t, stdout) }) } } func
(tb testing.TB, stdout, stderr string, rc int) { tb.Helper() f, err := os.CreateTemp("", "tmpfile-") if err != nil { tb.Fatal(err) } // close and remove the temporary file at the end of the program defer f.Close() defer os.Remove(f.Name()) data := []byte(stdout) if _, err := f.Write(data); err != nil { tb.Fatal(err) } args := []string{ "validate", "--input-format", "json", "--input-version", "v1_4", "--input-file", "/sbom", } cmd, stdout, stderr := runCycloneDXInDocker(tb, nil, "cyclonedx/cyclonedx-cli", f, args...) if cmd.ProcessState.ExitCode() != 0 { tb.Errorf("expected no validation failures for cyclonedx-cli but got rc=%d", rc) } if tb.Failed() { tb.Log("STDOUT:\n", stdout) tb.Log("STDERR:\n", stderr) tb.Log("COMMAND:", strings.Join(cmd.Args, " ")) } } // validate --input-format json --input-version v1_4 --input-file bom.json func validateCycloneDXJSON(t *testing.T, stdout string) { f, err := os.CreateTemp("", "tmpfile-") if err != nil { t.Fatal(err) } // close and remove the temporary file at the end of the program defer f.Close() defer os.Remove(f.Name()) data := []byte(stdout) if _, err := f.Write(data); err != nil { t.Fatal(err) } args := []string{ "validate", "--input-format", "json", "--input-version", "v1_4", "--input-file", "/sbom", } cmd, stdout, stderr := runCycloneDXInDocker(t, nil, "cyclonedx/cyclonedx-cli", f, args...) if strings.Contains(stdout, "BOM is not valid") { t.Errorf("expected no validation failures for cyclonedx-cli but found invalid BOM") } if t.Failed() { t.Log("STDOUT:\n", stdout) t.Log("STDERR:\n", stderr) t.Log("COMMAND:", strings.Join(cmd.Args, " ")) } }
assertValidCycloneDX
mod.rs
pub mod on_unimplemented; pub mod suggestions; use super::{ ConstEvalFailure, EvaluationResult, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes, Obligation, ObligationCause, ObligationCauseCode, OnUnimplementedDirective, OnUnimplementedNote, OutputTypeParameterMismatch, Overflow, PredicateObligation, SelectionContext, SelectionError, TraitNotObjectSafe, }; use crate::infer::error_reporting::{TyCategory, TypeAnnotationNeeded as ErrorCode}; use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use crate::infer::{self, InferCtxt, TyCtxtInferExt}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorReported}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::intravisit::Visitor; use rustc_hir::Node; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::error::ExpectedFound; use rustc_middle::ty::fold::TypeFolder; use rustc_middle::ty::{ self, fast_reject, AdtKind, SubtypePredicate, ToPolyTraitRef, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness, }; use rustc_session::DiagnosticMessageId; use rustc_span::symbol::{kw, sym}; use rustc_span::{ExpnKind, MultiSpan, Span, DUMMY_SP}; use std::fmt; use crate::traits::query::evaluate_obligation::InferCtxtExt as _; use crate::traits::query::normalize::AtExt as _; use on_unimplemented::InferCtxtExt as _; use suggestions::InferCtxtExt as _; pub use rustc_infer::traits::error_reporting::*; pub trait InferCtxtExt<'tcx> { fn report_fulfillment_errors( &self, errors: &[FulfillmentError<'tcx>], body_id: Option<hir::BodyId>, fallback_has_occurred: bool, ); fn report_overflow_error<T>( &self, obligation: &Obligation<'tcx, T>, suggest_increasing_limit: bool, ) -> ! where T: fmt::Display + TypeFoldable<'tcx>; fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !; fn report_selection_error( &self, obligation: &PredicateObligation<'tcx>, error: &SelectionError<'tcx>, fallback_has_occurred: bool, points_at_arg: bool, ); /// Given some node representing a fn-like thing in the HIR map, /// returns a span and `ArgKind` information that describes the /// arguments it expects. This can be supplied to /// `report_arg_count_mismatch`. fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)>; /// Reports an error when the number of arguments needed by a /// trait match doesn't match the number that the expression /// provides. fn report_arg_count_mismatch( &self, span: Span, found_span: Option<Span>, expected_args: Vec<ArgKind>, found_args: Vec<ArgKind>, is_closure: bool, ) -> DiagnosticBuilder<'tcx>; } impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { fn report_fulfillment_errors( &self, errors: &[FulfillmentError<'tcx>], body_id: Option<hir::BodyId>, fallback_has_occurred: bool, ) { #[derive(Debug)] struct ErrorDescriptor<'tcx> { predicate: ty::Predicate<'tcx>, index: Option<usize>, // None if this is an old error } let mut error_map: FxHashMap<_, Vec<_>> = self .reported_trait_errors .borrow() .iter() .map(|(&span, predicates)| { ( span, predicates .iter() .map(|&predicate| ErrorDescriptor { predicate, index: None }) .collect(), ) }) .collect(); for (index, error) in errors.iter().enumerate() { // We want to ignore desugarings here: spans are equivalent even // if one is the result of a desugaring and the other is not. let mut span = error.obligation.cause.span; let expn_data = span.ctxt().outer_expn_data(); if let ExpnKind::Desugaring(_) = expn_data.kind { span = expn_data.call_site; } error_map.entry(span).or_default().push(ErrorDescriptor { predicate: error.obligation.predicate, index: Some(index), }); self.reported_trait_errors .borrow_mut() .entry(span) .or_default() .push(error.obligation.predicate); } // We do this in 2 passes because we want to display errors in order, though // maybe it *is* better to sort errors by span or something. let mut is_suppressed = vec![false; errors.len()]; for (_, error_set) in error_map.iter() { // We want to suppress "duplicate" errors with the same span. for error in error_set { if let Some(index) = error.index { // Suppress errors that are either: // 1) strictly implied by another error. // 2) implied by an error with a smaller index. for error2 in error_set { if error2.index.map_or(false, |index2| is_suppressed[index2]) { // Avoid errors being suppressed by already-suppressed // errors, to prevent all errors from being suppressed // at once. continue; } if self.error_implies(error2.predicate, error.predicate) && !(error2.index >= error.index && self.error_implies(error.predicate, error2.predicate)) { info!("skipping {:?} (implied by {:?})", error, error2); is_suppressed[index] = true; break; } } } } } for (error, suppressed) in errors.iter().zip(is_suppressed) { if !suppressed { self.report_fulfillment_error(error, body_id, fallback_has_occurred); } } } /// Reports that an overflow has occurred and halts compilation. We /// halt compilation unconditionally because it is important that /// overflows never be masked -- they basically represent computations /// whose result could not be truly determined and thus we can't say /// if the program type checks or not -- and they are unusual /// occurrences in any case. fn report_overflow_error<T>( &self, obligation: &Obligation<'tcx, T>, suggest_increasing_limit: bool, ) -> ! where T: fmt::Display + TypeFoldable<'tcx>, { let predicate = self.resolve_vars_if_possible(obligation.predicate.clone()); let mut err = struct_span_err!( self.tcx.sess, obligation.cause.span, E0275, "overflow evaluating the requirement `{}`", predicate ); if suggest_increasing_limit { self.suggest_new_overflow_limit(&mut err); } self.note_obligation_cause_code( &mut err, &obligation.predicate, &obligation.cause.code, &mut vec![], &mut Default::default(), ); err.emit(); self.tcx.sess.abort_if_errors(); bug!(); } /// Reports that a cycle was detected which led to overflow and halts /// compilation. This is equivalent to `report_overflow_error` except /// that we can give a more helpful error message (and, in particular, /// we do not suggest increasing the overflow limit, which is not /// going to help). fn
(&self, cycle: &[PredicateObligation<'tcx>]) -> ! { let cycle = self.resolve_vars_if_possible(cycle.to_owned()); assert!(!cycle.is_empty()); debug!("report_overflow_error_cycle: cycle={:?}", cycle); self.report_overflow_error(&cycle[0], false); } fn report_selection_error( &self, obligation: &PredicateObligation<'tcx>, error: &SelectionError<'tcx>, fallback_has_occurred: bool, points_at_arg: bool, ) { let tcx = self.tcx; let span = obligation.cause.span; let mut err = match *error { SelectionError::Unimplemented => { if let ObligationCauseCode::CompareImplMethodObligation { item_name, impl_item_def_id, trait_item_def_id, } | ObligationCauseCode::CompareImplTypeObligation { item_name, impl_item_def_id, trait_item_def_id, } = obligation.cause.code { self.report_extra_impl_obligation( span, item_name, impl_item_def_id, trait_item_def_id, &format!("`{}`", obligation.predicate), ) .emit(); return; } let bound_predicate = obligation.predicate.bound_atom(); match bound_predicate.skip_binder() { ty::PredicateAtom::Trait(trait_predicate, _) => { let trait_predicate = bound_predicate.rebind(trait_predicate); let trait_predicate = self.resolve_vars_if_possible(trait_predicate); if self.tcx.sess.has_errors() && trait_predicate.references_error() { return; } let trait_ref = trait_predicate.to_poly_trait_ref(); let (post_message, pre_message, type_def) = self .get_parent_trait_ref(&obligation.cause.code) .map(|(t, s)| { ( format!(" in `{}`", t), format!("within `{}`, ", t), s.map(|s| (format!("within this `{}`", t), s)), ) }) .unwrap_or_default(); let OnUnimplementedNote { message, label, note, enclosing_scope } = self.on_unimplemented_note(trait_ref, obligation); let have_alt_message = message.is_some() || label.is_some(); let is_try_conversion = self.is_try_conversion(span, trait_ref.def_id()); let is_unsize = { Some(trait_ref.def_id()) == self.tcx.lang_items().unsize_trait() }; let (message, note) = if is_try_conversion { ( Some(format!( "`?` couldn't convert the error to `{}`", trait_ref.skip_binder().self_ty(), )), Some( "the question mark operation (`?`) implicitly performs a \ conversion on the error value using the `From` trait" .to_owned(), ), ) } else { (message, note) }; let mut err = struct_span_err!( self.tcx.sess, span, E0277, "{}", message.unwrap_or_else(|| format!( "the trait bound `{}` is not satisfied{}", trait_ref.without_const().to_predicate(tcx), post_message, )) ); if is_try_conversion { let none_error = self .tcx .get_diagnostic_item(sym::none_error) .map(|def_id| tcx.type_of(def_id)); let should_convert_option_to_result = Some(trait_ref.skip_binder().substs.type_at(1)) == none_error; let should_convert_result_to_option = Some(trait_ref.self_ty().skip_binder()) == none_error; if should_convert_option_to_result { err.span_suggestion_verbose( span.shrink_to_lo(), "consider converting the `Option<T>` into a `Result<T, _>` \ using `Option::ok_or` or `Option::ok_or_else`", ".ok_or_else(|| /* error value */)".to_string(), Applicability::HasPlaceholders, ); } else if should_convert_result_to_option { err.span_suggestion_verbose( span.shrink_to_lo(), "consider converting the `Result<T, _>` into an `Option<T>` \ using `Result::ok`", ".ok()".to_string(), Applicability::MachineApplicable, ); } if let Some(ret_span) = self.return_type_span(obligation) { err.span_label( ret_span, &format!( "expected `{}` because of this", trait_ref.skip_binder().self_ty() ), ); } } let explanation = if obligation.cause.code == ObligationCauseCode::MainFunctionType { "consider using `()`, or a `Result`".to_owned() } else { format!( "{}the trait `{}` is not implemented for `{}`", pre_message, trait_ref.print_only_trait_path(), trait_ref.skip_binder().self_ty(), ) }; if self.suggest_add_reference_to_arg( &obligation, &mut err, &trait_ref, points_at_arg, have_alt_message, ) { self.note_obligation_cause(&mut err, obligation); err.emit(); return; } if let Some(ref s) = label { // If it has a custom `#[rustc_on_unimplemented]` // error message, let's display it as the label! err.span_label(span, s.as_str()); if !matches!(trait_ref.skip_binder().self_ty().kind(), ty::Param(_)) { // When the self type is a type param We don't need to "the trait // `std::marker::Sized` is not implemented for `T`" as we will point // at the type param with a label to suggest constraining it. err.help(&explanation); } } else { err.span_label(span, explanation); } if let Some((msg, span)) = type_def { err.span_label(span, &msg); } if let Some(ref s) = note { // If it has a custom `#[rustc_on_unimplemented]` note, let's display it err.note(s.as_str()); } if let Some(ref s) = enclosing_scope { let body = tcx .hir() .opt_local_def_id(obligation.cause.body_id) .unwrap_or_else(|| { tcx.hir().body_owner_def_id(hir::BodyId { hir_id: obligation.cause.body_id, }) }); let enclosing_scope_span = tcx.hir().span_with_body(tcx.hir().local_def_id_to_hir_id(body)); err.span_label(enclosing_scope_span, s.as_str()); } self.suggest_dereferences(&obligation, &mut err, trait_ref, points_at_arg); self.suggest_fn_call(&obligation, &mut err, trait_ref, points_at_arg); self.suggest_remove_reference(&obligation, &mut err, trait_ref); self.suggest_semicolon_removal(&obligation, &mut err, span, trait_ref); self.note_version_mismatch(&mut err, &trait_ref); if Some(trait_ref.def_id()) == tcx.lang_items().try_trait() { self.suggest_await_before_try(&mut err, &obligation, trait_ref, span); } if self.suggest_impl_trait(&mut err, span, &obligation, trait_ref) { err.emit(); return; } if is_unsize { // If the obligation failed due to a missing implementation of the // `Unsize` trait, give a pointer to why that might be the case err.note( "all implementations of `Unsize` are provided \ automatically by the compiler, see \ <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \ for more information", ); } let is_fn_trait = [ self.tcx.lang_items().fn_trait(), self.tcx.lang_items().fn_mut_trait(), self.tcx.lang_items().fn_once_trait(), ] .contains(&Some(trait_ref.def_id())); let is_target_feature_fn = if let ty::FnDef(def_id, _) = *trait_ref.skip_binder().self_ty().kind() { !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty() } else { false }; if is_fn_trait && is_target_feature_fn { err.note( "`#[target_feature]` functions do not implement the `Fn` traits", ); } // Try to report a help message if !trait_ref.has_infer_types_or_consts() && self.predicate_can_apply(obligation.param_env, trait_ref) { // If a where-clause may be useful, remind the // user that they can add it. // // don't display an on-unimplemented note, as // these notes will often be of the form // "the type `T` can't be frobnicated" // which is somewhat confusing. self.suggest_restricting_param_bound( &mut err, trait_ref, obligation.cause.body_id, ); } else { if !have_alt_message { // Can't show anything else useful, try to find similar impls. let impl_candidates = self.find_similar_impl_candidates(trait_ref); self.report_similar_impl_candidates(impl_candidates, &mut err); } // Changing mutability doesn't make a difference to whether we have // an `Unsize` impl (Fixes ICE in #71036) if !is_unsize { self.suggest_change_mut( &obligation, &mut err, trait_ref, points_at_arg, ); } } // If this error is due to `!: Trait` not implemented but `(): Trait` is // implemented, and fallback has occurred, then it could be due to a // variable that used to fallback to `()` now falling back to `!`. Issue a // note informing about the change in behaviour. if trait_predicate.skip_binder().self_ty().is_never() && fallback_has_occurred { let predicate = trait_predicate.map_bound(|mut trait_pred| { trait_pred.trait_ref.substs = self.tcx.mk_substs_trait( self.tcx.mk_unit(), &trait_pred.trait_ref.substs[1..], ); trait_pred }); let unit_obligation = obligation.with(predicate.without_const().to_predicate(tcx)); if self.predicate_may_hold(&unit_obligation) { err.note( "the trait is implemented for `()`. \ Possibly this error has been caused by changes to \ Rust's type-inference algorithm (see issue #48950 \ <https://github.com/rust-lang/rust/issues/48950> \ for more information). Consider whether you meant to use \ the type `()` here instead.", ); } } err } ty::PredicateAtom::Subtype(predicate) => { // Errors for Subtype predicates show up as // `FulfillmentErrorCode::CodeSubtypeError`, // not selection error. span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate) } ty::PredicateAtom::RegionOutlives(predicate) => { let predicate = bound_predicate.rebind(predicate); let predicate = self.resolve_vars_if_possible(predicate); let err = self .region_outlives_predicate(&obligation.cause, predicate) .err() .unwrap(); struct_span_err!( self.tcx.sess, span, E0279, "the requirement `{}` is not satisfied (`{}`)", predicate, err, ) } ty::PredicateAtom::Projection(..) | ty::PredicateAtom::TypeOutlives(..) => { let predicate = self.resolve_vars_if_possible(obligation.predicate); struct_span_err!( self.tcx.sess, span, E0280, "the requirement `{}` is not satisfied", predicate ) } ty::PredicateAtom::ObjectSafe(trait_def_id) => { let violations = self.tcx.object_safety_violations(trait_def_id); report_object_safety_error(self.tcx, span, trait_def_id, violations) } ty::PredicateAtom::ClosureKind(closure_def_id, closure_substs, kind) => { let found_kind = self.closure_kind(closure_substs).unwrap(); let closure_span = self.tcx.sess.source_map().guess_head_span( self.tcx.hir().span_if_local(closure_def_id).unwrap(), ); let hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local()); let mut err = struct_span_err!( self.tcx.sess, closure_span, E0525, "expected a closure that implements the `{}` trait, \ but this closure only implements `{}`", kind, found_kind ); err.span_label( closure_span, format!("this closure implements `{}`, not `{}`", found_kind, kind), ); err.span_label( obligation.cause.span, format!("the requirement to implement `{}` derives from here", kind), ); // Additional context information explaining why the closure only implements // a particular trait. if let Some(typeck_results) = self.in_progress_typeck_results { let typeck_results = typeck_results.borrow(); match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) { (ty::ClosureKind::FnOnce, Some((span, name))) => { err.span_label( *span, format!( "closure is `FnOnce` because it moves the \ variable `{}` out of its environment", name ), ); } (ty::ClosureKind::FnMut, Some((span, name))) => { err.span_label( *span, format!( "closure is `FnMut` because it mutates the \ variable `{}` here", name ), ); } _ => {} } } err.emit(); return; } ty::PredicateAtom::WellFormed(ty) => { if !self.tcx.sess.opts.debugging_opts.chalk { // WF predicates cannot themselves make // errors. They can only block due to // ambiguity; otherwise, they always // degenerate into other obligations // (which may fail). span_bug!(span, "WF predicate not satisfied for {:?}", ty); } else { // FIXME: we'll need a better message which takes into account // which bounds actually failed to hold. self.tcx.sess.struct_span_err( span, &format!("the type `{}` is not well-formed (chalk)", ty), ) } } ty::PredicateAtom::ConstEvaluatable(..) => { // Errors for `ConstEvaluatable` predicates show up as // `SelectionError::ConstEvalFailure`, // not `Unimplemented`. span_bug!( span, "const-evaluatable requirement gave wrong error: `{:?}`", obligation ) } ty::PredicateAtom::ConstEquate(..) => { // Errors for `ConstEquate` predicates show up as // `SelectionError::ConstEvalFailure`, // not `Unimplemented`. span_bug!( span, "const-equate requirement gave wrong error: `{:?}`", obligation ) } ty::PredicateAtom::TypeWellFormedFromEnv(..) => span_bug!( span, "TypeWellFormedFromEnv predicate should only exist in the environment" ), } } OutputTypeParameterMismatch(found_trait_ref, expected_trait_ref, _) => { let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref); let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref); if expected_trait_ref.self_ty().references_error() { return; } let found_trait_ty = match found_trait_ref.self_ty().no_bound_vars() { Some(ty) => ty, None => return, }; let found_did = match *found_trait_ty.kind() { ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did), ty::Adt(def, _) => Some(def.did), _ => None, }; let found_span = found_did .and_then(|did| self.tcx.hir().span_if_local(did)) .map(|sp| self.tcx.sess.source_map().guess_head_span(sp)); // the sp could be an fn def if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) { // We check closures twice, with obligations flowing in different directions, // but we want to complain about them only once. return; } self.reported_closure_mismatch.borrow_mut().insert((span, found_span)); let found = match found_trait_ref.skip_binder().substs.type_at(1).kind() { ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()], _ => vec![ArgKind::empty()], }; let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1); let expected = match expected_ty.kind() { ty::Tuple(ref tys) => tys .iter() .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span))) .collect(), _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())], }; if found.len() == expected.len() { self.report_closure_arg_mismatch( span, found_span, found_trait_ref, expected_trait_ref, ) } else { let (closure_span, found) = found_did .and_then(|did| { let node = self.tcx.hir().get_if_local(did)?; let (found_span, found) = self.get_fn_like_arguments(node)?; Some((Some(found_span), found)) }) .unwrap_or((found_span, found)); self.report_arg_count_mismatch( span, closure_span, expected, found, found_trait_ty.is_closure(), ) } } TraitNotObjectSafe(did) => { let violations = self.tcx.object_safety_violations(did); report_object_safety_error(self.tcx, span, did, violations) } ConstEvalFailure(ErrorHandled::TooGeneric) => { bug!("too generic should have been handled in `is_const_evaluatable`"); } // Already reported in the query. ConstEvalFailure(ErrorHandled::Reported(ErrorReported)) => { // FIXME(eddyb) remove this once `ErrorReported` becomes a proof token. self.tcx.sess.delay_span_bug(span, "`ErrorReported` without an error"); return; } // Already reported in the query, but only as a lint. // This shouldn't actually happen for constants used in types, modulo // bugs. The `delay_span_bug` here ensures it won't be ignored. ConstEvalFailure(ErrorHandled::Linted) => { self.tcx.sess.delay_span_bug(span, "constant in type had error reported as lint"); return; } Overflow => { bug!("overflow should be handled before the `report_selection_error` path"); } }; self.note_obligation_cause(&mut err, obligation); self.point_at_returns_when_relevant(&mut err, &obligation); err.emit(); } /// Given some node representing a fn-like thing in the HIR map, /// returns a span and `ArgKind` information that describes the /// arguments it expects. This can be supplied to /// `report_arg_count_mismatch`. fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)> { let sm = self.tcx.sess.source_map(); let hir = self.tcx.hir(); Some(match node { Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure(_, ref _decl, id, span, _), .. }) => ( sm.guess_head_span(span), hir.body(id) .params .iter() .map(|arg| { if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } = *arg.pat { Some(ArgKind::Tuple( Some(span), args.iter() .map(|pat| { sm.span_to_snippet(pat.span) .ok() .map(|snippet| (snippet, "_".to_owned())) }) .collect::<Option<Vec<_>>>()?, )) } else { let name = sm.span_to_snippet(arg.pat.span).ok()?; Some(ArgKind::Arg(name, "_".to_owned())) } }) .collect::<Option<Vec<ArgKind>>>()?, ), Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. }) | Node::ImplItem(&hir::ImplItem { span, kind: hir::ImplItemKind::Fn(ref sig, _), .. }) | Node::TraitItem(&hir::TraitItem { span, kind: hir::TraitItemKind::Fn(ref sig, _), .. }) => ( sm.guess_head_span(span), sig.decl .inputs .iter() .map(|arg| match arg.clone().kind { hir::TyKind::Tup(ref tys) => ArgKind::Tuple( Some(arg.span), vec![("_".to_owned(), "_".to_owned()); tys.len()], ), _ => ArgKind::empty(), }) .collect::<Vec<ArgKind>>(), ), Node::Ctor(ref variant_data) => { let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id)); let span = sm.guess_head_span(span); (span, vec![ArgKind::empty(); variant_data.fields().len()]) } _ => panic!("non-FnLike node found: {:?}", node), }) } /// Reports an error when the number of arguments needed by a /// trait match doesn't match the number that the expression /// provides. fn report_arg_count_mismatch( &self, span: Span, found_span: Option<Span>, expected_args: Vec<ArgKind>, found_args: Vec<ArgKind>, is_closure: bool, ) -> DiagnosticBuilder<'tcx> { let kind = if is_closure { "closure" } else { "function" }; let args_str = |arguments: &[ArgKind], other: &[ArgKind]| { let arg_length = arguments.len(); let distinct = matches!(other, &[ArgKind::Tuple(..)]); match (arg_length, arguments.get(0)) { (1, Some(&ArgKind::Tuple(_, ref fields))) => { format!("a single {}-tuple as argument", fields.len()) } _ => format!( "{} {}argument{}", arg_length, if distinct && arg_length > 1 { "distinct " } else { "" }, pluralize!(arg_length) ), } }; let expected_str = args_str(&expected_args, &found_args); let found_str = args_str(&found_args, &expected_args); let mut err = struct_span_err!( self.tcx.sess, span, E0593, "{} is expected to take {}, but it takes {}", kind, expected_str, found_str, ); err.span_label(span, format!("expected {} that takes {}", kind, expected_str)); if let Some(found_span) = found_span { err.span_label(found_span, format!("takes {}", found_str)); // move |_| { ... } // ^^^^^^^^-- def_span // // move |_| { ... } // ^^^^^-- prefix let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span); // move |_| { ... } // ^^^-- pipe_span let pipe_span = if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span }; // Suggest to take and ignore the arguments with expected_args_length `_`s if // found arguments is empty (assume the user just wants to ignore args in this case). // For example, if `expected_args_length` is 2, suggest `|_, _|`. if found_args.is_empty() && is_closure { let underscores = vec!["_"; expected_args.len()].join(", "); err.span_suggestion_verbose( pipe_span, &format!( "consider changing the closure to take and ignore the expected argument{}", pluralize!(expected_args.len()) ), format!("|{}|", underscores), Applicability::MachineApplicable, ); } if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] { if fields.len() == expected_args.len() { let sugg = fields .iter() .map(|(name, _)| name.to_owned()) .collect::<Vec<String>>() .join(", "); err.span_suggestion_verbose( found_span, "change the closure to take multiple arguments instead of a single tuple", format!("|{}|", sugg), Applicability::MachineApplicable, ); } } if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] { if fields.len() == found_args.len() && is_closure { let sugg = format!( "|({}){}|", found_args .iter() .map(|arg| match arg { ArgKind::Arg(name, _) => name.to_owned(), _ => "_".to_owned(), }) .collect::<Vec<String>>() .join(", "), // add type annotations if available if found_args.iter().any(|arg| match arg { ArgKind::Arg(_, ty) => ty != "_", _ => false, }) { format!( ": ({})", fields .iter() .map(|(_, ty)| ty.to_owned()) .collect::<Vec<String>>() .join(", ") ) } else { String::new() }, ); err.span_suggestion_verbose( found_span, "change the closure to accept a tuple instead of individual arguments", sugg, Applicability::MachineApplicable, ); } } } err } } trait InferCtxtPrivExt<'tcx> { // returns if `cond` not occurring implies that `error` does not occur - i.e., that // `error` occurring implies that `cond` occurs. fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool; fn report_fulfillment_error( &self, error: &FulfillmentError<'tcx>, body_id: Option<hir::BodyId>, fallback_has_occurred: bool, ); fn report_projection_error( &self, obligation: &PredicateObligation<'tcx>, error: &MismatchedProjectionTypes<'tcx>, ); fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool; fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>; fn find_similar_impl_candidates( &self, trait_ref: ty::PolyTraitRef<'tcx>, ) -> Vec<ty::TraitRef<'tcx>>; fn report_similar_impl_candidates( &self, impl_candidates: Vec<ty::TraitRef<'tcx>>, err: &mut DiagnosticBuilder<'_>, ); /// Gets the parent trait chain start fn get_parent_trait_ref( &self, code: &ObligationCauseCode<'tcx>, ) -> Option<(String, Option<Span>)>; /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait /// with the same path as `trait_ref`, a help message about /// a probable version mismatch is added to `err` fn note_version_mismatch( &self, err: &mut DiagnosticBuilder<'_>, trait_ref: &ty::PolyTraitRef<'tcx>, ); /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the /// `trait_ref`. /// /// For this to work, `new_self_ty` must have no escaping bound variables. fn mk_trait_obligation_with_new_self_ty( &self, param_env: ty::ParamEnv<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, new_self_ty: Ty<'tcx>, ) -> PredicateObligation<'tcx>; fn maybe_report_ambiguity( &self, obligation: &PredicateObligation<'tcx>, body_id: Option<hir::BodyId>, ); fn predicate_can_apply( &self, param_env: ty::ParamEnv<'tcx>, pred: ty::PolyTraitRef<'tcx>, ) -> bool; fn note_obligation_cause( &self, err: &mut DiagnosticBuilder<'tcx>, obligation: &PredicateObligation<'tcx>, ); fn suggest_unsized_bound_if_applicable( &self, err: &mut DiagnosticBuilder<'tcx>, obligation: &PredicateObligation<'tcx>, ); fn is_recursive_obligation( &self, obligated_types: &mut Vec<&ty::TyS<'tcx>>, cause_code: &ObligationCauseCode<'tcx>, ) -> bool; } impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { // returns if `cond` not occurring implies that `error` does not occur - i.e., that // `error` occurring implies that `cond` occurs. fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool { if cond == error { return true; } // FIXME: It should be possible to deal with `ForAll` in a cleaner way. let bound_error = error.bound_atom(); let (cond, error) = match (cond.skip_binders(), bound_error.skip_binder()) { (ty::PredicateAtom::Trait(..), ty::PredicateAtom::Trait(error, _)) => { (cond, bound_error.rebind(error)) } _ => { // FIXME: make this work in other cases too. return false; } }; for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) { let bound_predicate = obligation.predicate.bound_atom(); if let ty::PredicateAtom::Trait(implication, _) = bound_predicate.skip_binder() { let error = error.to_poly_trait_ref(); let implication = bound_predicate.rebind(implication.trait_ref); // FIXME: I'm just not taking associated types at all here. // Eventually I'll need to implement param-env-aware // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic. let param_env = ty::ParamEnv::empty(); if self.can_sub(param_env, error, implication).is_ok() { debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication); return true; } } } false } fn report_fulfillment_error( &self, error: &FulfillmentError<'tcx>, body_id: Option<hir::BodyId>, fallback_has_occurred: bool, ) { debug!("report_fulfillment_error({:?})", error); match error.code { FulfillmentErrorCode::CodeSelectionError(ref selection_error) => { self.report_selection_error( &error.obligation, selection_error, fallback_has_occurred, error.points_at_arg_span, ); } FulfillmentErrorCode::CodeProjectionError(ref e) => { self.report_projection_error(&error.obligation, e); } FulfillmentErrorCode::CodeAmbiguity => { self.maybe_report_ambiguity(&error.obligation, body_id); } FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => { self.report_mismatched_types( &error.obligation.cause, expected_found.expected, expected_found.found, err.clone(), ) .emit(); } FulfillmentErrorCode::CodeConstEquateError(ref expected_found, ref err) => { self.report_mismatched_consts( &error.obligation.cause, expected_found.expected, expected_found.found, err.clone(), ) .emit(); } } } fn report_projection_error( &self, obligation: &PredicateObligation<'tcx>, error: &MismatchedProjectionTypes<'tcx>, ) { let predicate = self.resolve_vars_if_possible(obligation.predicate); if predicate.references_error() { return; } self.probe(|_| { let err_buf; let mut err = &error.err; let mut values = None; // try to find the mismatched types to report the error with. // // this can fail if the problem was higher-ranked, in which // cause I have no idea for a good error message. let bound_predicate = predicate.bound_atom(); if let ty::PredicateAtom::Projection(data) = bound_predicate.skip_binder() { let mut selcx = SelectionContext::new(self); let (data, _) = self.replace_bound_vars_with_fresh_vars( obligation.cause.span, infer::LateBoundRegionConversionTime::HigherRankedType, bound_predicate.rebind(data), ); let mut obligations = vec![]; let normalized_ty = super::normalize_projection_type( &mut selcx, obligation.param_env, data.projection_ty, obligation.cause.clone(), 0, &mut obligations, ); debug!( "report_projection_error obligation.cause={:?} obligation.param_env={:?}", obligation.cause, obligation.param_env ); debug!( "report_projection_error normalized_ty={:?} data.ty={:?}", normalized_ty, data.ty ); let is_normalized_ty_expected = !matches!(obligation.cause.code, ObligationCauseCode::ItemObligation(_) | ObligationCauseCode::BindingObligation(_, _) | ObligationCauseCode::ObjectCastObligation(_)); if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp( is_normalized_ty_expected, normalized_ty, data.ty, ) { values = Some(infer::ValuePairs::Types(ExpectedFound::new( is_normalized_ty_expected, normalized_ty, data.ty, ))); err_buf = error; err = &err_buf; } } let msg = format!("type mismatch resolving `{}`", predicate); let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg); let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id); if fresh { let mut diag = struct_span_err!( self.tcx.sess, obligation.cause.span, E0271, "type mismatch resolving `{}`", predicate ); self.note_type_err(&mut diag, &obligation.cause, None, values, err); self.note_obligation_cause(&mut diag, obligation); diag.emit(); } }); } fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool { /// returns the fuzzy category of a given type, or None /// if the type can be equated to any type. fn type_category(t: Ty<'_>) -> Option<u32> { match t.kind() { ty::Bool => Some(0), ty::Char => Some(1), ty::Str => Some(2), ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3), ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4), ty::Ref(..) | ty::RawPtr(..) => Some(5), ty::Array(..) | ty::Slice(..) => Some(6), ty::FnDef(..) | ty::FnPtr(..) => Some(7), ty::Dynamic(..) => Some(8), ty::Closure(..) => Some(9), ty::Tuple(..) => Some(10), ty::Projection(..) => Some(11), ty::Param(..) => Some(12), ty::Opaque(..) => Some(13), ty::Never => Some(14), ty::Adt(adt, ..) => match adt.adt_kind() { AdtKind::Struct => Some(15), AdtKind::Union => Some(16), AdtKind::Enum => Some(17), }, ty::Generator(..) => Some(18), ty::Foreign(..) => Some(19), ty::GeneratorWitness(..) => Some(20), ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None, } } match (type_category(a), type_category(b)) { (Some(cat_a), Some(cat_b)) => match (a.kind(), b.kind()) { (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b, _ => cat_a == cat_b, }, // infer and error can be equated to all types _ => true, } } fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> { self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind { hir::GeneratorKind::Gen => "a generator", hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block", hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function", hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure", }) } fn find_similar_impl_candidates( &self, trait_ref: ty::PolyTraitRef<'tcx>, ) -> Vec<ty::TraitRef<'tcx>> { let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true); let all_impls = self.tcx.all_impls(trait_ref.def_id()); match simp { Some(simp) => all_impls .filter_map(|def_id| { let imp = self.tcx.impl_trait_ref(def_id).unwrap(); let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true); if let Some(imp_simp) = imp_simp { if simp != imp_simp { return None; } } if self.tcx.impl_polarity(def_id) == ty::ImplPolarity::Negative { return None; } Some(imp) }) .collect(), None => all_impls .filter_map(|def_id| { if self.tcx.impl_polarity(def_id) == ty::ImplPolarity::Negative { return None; } self.tcx.impl_trait_ref(def_id) }) .collect(), } } fn report_similar_impl_candidates( &self, impl_candidates: Vec<ty::TraitRef<'tcx>>, err: &mut DiagnosticBuilder<'_>, ) { if impl_candidates.is_empty() { return; } let len = impl_candidates.len(); let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 }; let normalize = |candidate| { self.tcx.infer_ctxt().enter(|ref infcx| { let normalized = infcx .at(&ObligationCause::dummy(), ty::ParamEnv::empty()) .normalize(candidate) .ok(); match normalized { Some(normalized) => format!("\n {}", normalized.value), None => format!("\n {}", candidate), } }) }; // Sort impl candidates so that ordering is consistent for UI tests. let mut normalized_impl_candidates = impl_candidates.iter().copied().map(normalize).collect::<Vec<String>>(); // Sort before taking the `..end` range, // because the ordering of `impl_candidates` may not be deterministic: // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507 normalized_impl_candidates.sort(); err.help(&format!( "the following implementations were found:{}{}", normalized_impl_candidates[..end].join(""), if len > 5 { format!("\nand {} others", len - 4) } else { String::new() } )); } /// Gets the parent trait chain start fn get_parent_trait_ref( &self, code: &ObligationCauseCode<'tcx>, ) -> Option<(String, Option<Span>)> { match code { ObligationCauseCode::BuiltinDerivedObligation(data) => { let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref); match self.get_parent_trait_ref(&data.parent_code) { Some(t) => Some(t), None => { let ty = parent_trait_ref.skip_binder().self_ty(); let span = TyCategory::from_ty(ty).map(|(_, def_id)| self.tcx.def_span(def_id)); Some((ty.to_string(), span)) } } } _ => None, } } /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait /// with the same path as `trait_ref`, a help message about /// a probable version mismatch is added to `err` fn note_version_mismatch( &self, err: &mut DiagnosticBuilder<'_>, trait_ref: &ty::PolyTraitRef<'tcx>, ) { let get_trait_impl = |trait_def_id| { self.tcx.find_map_relevant_impl(trait_def_id, trait_ref.skip_binder().self_ty(), Some) }; let required_trait_path = self.tcx.def_path_str(trait_ref.def_id()); let all_traits = self.tcx.all_traits(LOCAL_CRATE); let traits_with_same_path: std::collections::BTreeSet<_> = all_traits .iter() .filter(|trait_def_id| **trait_def_id != trait_ref.def_id()) .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path) .collect(); for trait_with_same_path in traits_with_same_path { if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) { let impl_span = self.tcx.def_span(impl_def_id); err.span_help(impl_span, "trait impl with same name found"); let trait_crate = self.tcx.crate_name(trait_with_same_path.krate); let crate_msg = format!( "perhaps two different versions of crate `{}` are being used?", trait_crate ); err.note(&crate_msg); } } } fn mk_trait_obligation_with_new_self_ty( &self, param_env: ty::ParamEnv<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, new_self_ty: Ty<'tcx>, ) -> PredicateObligation<'tcx> { assert!(!new_self_ty.has_escaping_bound_vars()); let trait_ref = trait_ref.map_bound_ref(|tr| ty::TraitRef { substs: self.tcx.mk_substs_trait(new_self_ty, &tr.substs[1..]), ..*tr }); Obligation::new( ObligationCause::dummy(), param_env, trait_ref.without_const().to_predicate(self.tcx), ) } fn maybe_report_ambiguity( &self, obligation: &PredicateObligation<'tcx>, body_id: Option<hir::BodyId>, ) { // Unable to successfully determine, probably means // insufficient type information, but could mean // ambiguous impls. The latter *ought* to be a // coherence violation, so we don't report it here. let predicate = self.resolve_vars_if_possible(obligation.predicate); let span = obligation.cause.span; debug!( "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})", predicate, obligation, body_id, obligation.cause.code, ); // Ambiguity errors are often caused as fallout from earlier // errors. So just ignore them if this infcx is tainted. if self.is_tainted_by_errors() { return; } let bound_predicate = predicate.bound_atom(); let mut err = match bound_predicate.skip_binder() { ty::PredicateAtom::Trait(data, _) => { let trait_ref = bound_predicate.rebind(data.trait_ref); debug!("trait_ref {:?}", trait_ref); if predicate.references_error() { return; } // Typically, this ambiguity should only happen if // there are unresolved type inference variables // (otherwise it would suggest a coherence // failure). But given #21974 that is not necessarily // the case -- we can have multiple where clauses that // are only distinguished by a region, which results // in an ambiguity even when all types are fully // known, since we don't dispatch based on region // relationships. // Pick the first substitution that still contains inference variables as the one // we're going to emit an error for. If there are none (see above), fall back to // the substitution for `Self`. let subst = { let substs = data.trait_ref.substs; substs .iter() .find(|s| s.has_infer_types_or_consts()) .unwrap_or_else(|| substs[0]) }; // This is kind of a hack: it frequently happens that some earlier // error prevents types from being fully inferred, and then we get // a bunch of uninteresting errors saying something like "<generic // #0> doesn't implement Sized". It may even be true that we // could just skip over all checks where the self-ty is an // inference variable, but I was afraid that there might be an // inference variable created, registered as an obligation, and // then never forced by writeback, and hence by skipping here we'd // be ignoring the fact that we don't KNOW the type works // out. Though even that would probably be harmless, given that // we're only talking about builtin traits, which are known to be // inhabited. We used to check for `self.tcx.sess.has_errors()` to // avoid inundating the user with unnecessary errors, but we now // check upstream for type errors and don't add the obligations to // begin with in those cases. if self.tcx.lang_items().sized_trait() == Some(trait_ref.def_id()) { self.emit_inference_failure_err(body_id, span, subst, ErrorCode::E0282).emit(); return; } let mut err = self.emit_inference_failure_err(body_id, span, subst, ErrorCode::E0283); err.note(&format!("cannot satisfy `{}`", predicate)); if let ObligationCauseCode::ItemObligation(def_id) = obligation.cause.code { self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id()); } else if let ( Ok(ref snippet), ObligationCauseCode::BindingObligation(ref def_id, _), ) = (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code) { let generics = self.tcx.generics_of(*def_id); if generics.params.iter().any(|p| p.name != kw::SelfUpper) && !snippet.ends_with('>') { // FIXME: To avoid spurious suggestions in functions where type arguments // where already supplied, we check the snippet to make sure it doesn't // end with a turbofish. Ideally we would have access to a `PathSegment` // instead. Otherwise we would produce the following output: // // error[E0283]: type annotations needed // --> $DIR/issue-54954.rs:3:24 // | // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>(); // | ^^^^^^^^^^^^^^^^^^^^^^^^^^ // | | // | cannot infer type // | help: consider specifying the type argument // | in the function call: // | `Tt::const_val::<[i8; 123]>::<T>` // ... // LL | const fn const_val<T: Sized>() -> usize { // | - required by this bound in `Tt::const_val` // | // = note: cannot satisfy `_: Tt` err.span_suggestion_verbose( span.shrink_to_hi(), &format!( "consider specifying the type argument{} in the function call", pluralize!(generics.params.len()), ), format!( "::<{}>", generics .params .iter() .map(|p| p.name.to_string()) .collect::<Vec<String>>() .join(", ") ), Applicability::HasPlaceholders, ); } } err } ty::PredicateAtom::WellFormed(arg) => { // Same hacky approach as above to avoid deluging user // with error messages. if arg.references_error() || self.tcx.sess.has_errors() { return; } self.emit_inference_failure_err(body_id, span, arg, ErrorCode::E0282) } ty::PredicateAtom::Subtype(data) => { if data.references_error() || self.tcx.sess.has_errors() { // no need to overload user in such cases return; } let SubtypePredicate { a_is_expected: _, a, b } = data; // both must be type variables, or the other would've been instantiated assert!(a.is_ty_var() && b.is_ty_var()); self.emit_inference_failure_err(body_id, span, a.into(), ErrorCode::E0282) } ty::PredicateAtom::Projection(data) => { let trait_ref = bound_predicate.rebind(data).to_poly_trait_ref(self.tcx); let self_ty = trait_ref.skip_binder().self_ty(); let ty = data.ty; if predicate.references_error() { return; } if self_ty.needs_infer() && ty.needs_infer() { // We do this for the `foo.collect()?` case to produce a suggestion. let mut err = self.emit_inference_failure_err( body_id, span, self_ty.into(), ErrorCode::E0284, ); err.note(&format!("cannot satisfy `{}`", predicate)); err } else { let mut err = struct_span_err!( self.tcx.sess, span, E0284, "type annotations needed: cannot satisfy `{}`", predicate, ); err.span_label(span, &format!("cannot satisfy `{}`", predicate)); err } } _ => { if self.tcx.sess.has_errors() { return; } let mut err = struct_span_err!( self.tcx.sess, span, E0284, "type annotations needed: cannot satisfy `{}`", predicate, ); err.span_label(span, &format!("cannot satisfy `{}`", predicate)); err } }; self.note_obligation_cause(&mut err, obligation); err.emit(); } /// Returns `true` if the trait predicate may apply for *some* assignment /// to the type parameters. fn predicate_can_apply( &self, param_env: ty::ParamEnv<'tcx>, pred: ty::PolyTraitRef<'tcx>, ) -> bool { struct ParamToVarFolder<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>, } impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> { fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.infcx.tcx } fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { if let ty::Param(ty::ParamTy { name, .. }) = *ty.kind() { let infcx = self.infcx; self.var_map.entry(ty).or_insert_with(|| { infcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeParameterDefinition(name, None), span: DUMMY_SP, }) }) } else { ty.super_fold_with(self) } } } self.probe(|_| { let mut selcx = SelectionContext::new(self); let cleaned_pred = pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() }); let cleaned_pred = super::project::normalize( &mut selcx, param_env, ObligationCause::dummy(), cleaned_pred, ) .value; let obligation = Obligation::new( ObligationCause::dummy(), param_env, cleaned_pred.without_const().to_predicate(selcx.tcx()), ); self.predicate_may_hold(&obligation) }) } fn note_obligation_cause( &self, err: &mut DiagnosticBuilder<'tcx>, obligation: &PredicateObligation<'tcx>, ) { // First, attempt to add note to this error with an async-await-specific // message, and fall back to regular note otherwise. if !self.maybe_note_obligation_cause_for_async_await(err, obligation) { self.note_obligation_cause_code( err, &obligation.predicate, &obligation.cause.code, &mut vec![], &mut Default::default(), ); self.suggest_unsized_bound_if_applicable(err, obligation); } } fn suggest_unsized_bound_if_applicable( &self, err: &mut DiagnosticBuilder<'tcx>, obligation: &PredicateObligation<'tcx>, ) { let (pred, item_def_id, span) = match (obligation.predicate.skip_binders(), obligation.cause.code.peel_derives()) { ( ty::PredicateAtom::Trait(pred, _), &ObligationCauseCode::BindingObligation(item_def_id, span), ) => (pred, item_def_id, span), _ => return, }; let node = match ( self.tcx.hir().get_if_local(item_def_id), Some(pred.def_id()) == self.tcx.lang_items().sized_trait(), ) { (Some(node), true) => node, _ => return, }; let generics = match node.generics() { Some(generics) => generics, None => return, }; for param in generics.params { if param.span != span || param.bounds.iter().any(|bound| { bound.trait_ref().and_then(|trait_ref| trait_ref.trait_def_id()) == self.tcx.lang_items().sized_trait() }) { continue; } match node { hir::Node::Item( item @ hir::Item { kind: hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..), .. }, ) => { // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);` // is not. let mut visitor = FindTypeParam { param: param.name.ident().name, invalid_spans: vec![], nested: false, }; visitor.visit_item(item); if !visitor.invalid_spans.is_empty() { let mut multispan: MultiSpan = param.span.into(); multispan.push_span_label( param.span, format!("this could be changed to `{}: ?Sized`...", param.name.ident()), ); for sp in visitor.invalid_spans { multispan.push_span_label( sp, format!( "...if indirection was used here: `Box<{}>`", param.name.ident(), ), ); } err.span_help( multispan, &format!( "you could relax the implicit `Sized` bound on `{T}` if it were \ used through indirection like `&{T}` or `Box<{T}>`", T = param.name.ident(), ), ); return; } } _ => {} } let (span, separator) = match param.bounds { [] => (span.shrink_to_hi(), ":"), [.., bound] => (bound.span().shrink_to_hi(), " +"), }; err.span_suggestion_verbose( span, "consider relaxing the implicit `Sized` restriction", format!("{} ?Sized", separator), Applicability::MachineApplicable, ); return; } } fn is_recursive_obligation( &self, obligated_types: &mut Vec<&ty::TyS<'tcx>>, cause_code: &ObligationCauseCode<'tcx>, ) -> bool { if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code { let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref); if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) { return true; } } false } } /// Look for type `param` in an ADT being used only through a reference to confirm that suggesting /// `param: ?Sized` would be a valid constraint. struct FindTypeParam { param: rustc_span::Symbol, invalid_spans: Vec<Span>, nested: bool, } impl<'v> Visitor<'v> for FindTypeParam { type Map = rustc_hir::intravisit::ErasedMap<'v>; fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> { hir::intravisit::NestedVisitorMap::None } fn visit_ty(&mut self, ty: &hir::Ty<'_>) { // We collect the spans of all uses of the "bare" type param, like in `field: T` or // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized` // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors // in that case should make what happened clear enough. match ty.kind { hir::TyKind::Ptr(_) | hir::TyKind::Rptr(..) | hir::TyKind::TraitObject(..) => {} hir::TyKind::Path(hir::QPath::Resolved(None, path)) if path.segments.len() == 1 && path.segments[0].ident.name == self.param => { if !self.nested { self.invalid_spans.push(ty.span); } } hir::TyKind::Path(_) => { let prev = self.nested; self.nested = true; hir::intravisit::walk_ty(self, ty); self.nested = prev; } _ => { hir::intravisit::walk_ty(self, ty); } } } } pub fn recursive_type_with_infinite_size_error( tcx: TyCtxt<'tcx>, type_def_id: DefId, spans: Vec<Span>, ) { assert!(type_def_id.is_local()); let span = tcx.hir().span_if_local(type_def_id).unwrap(); let span = tcx.sess.source_map().guess_head_span(span); let path = tcx.def_path_str(type_def_id); let mut err = struct_span_err!(tcx.sess, span, E0072, "recursive type `{}` has infinite size", path); err.span_label(span, "recursive type has infinite size"); for &span in &spans { err.span_label(span, "recursive without indirection"); } let msg = format!( "insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `{}` representable", path, ); if spans.len() <= 4 { err.multipart_suggestion( &msg, spans .iter() .flat_map(|&span| { vec![ (span.shrink_to_lo(), "Box<".to_string()), (span.shrink_to_hi(), ">".to_string()), ] .into_iter() }) .collect(), Applicability::HasPlaceholders, ); } else { err.help(&msg); } err.emit(); } /// Summarizes information #[derive(Clone)] pub enum ArgKind { /// An argument of non-tuple type. Parameters are (name, ty) Arg(String, String), /// An argument of tuple type. For a "found" argument, the span is /// the locationo in the source of the pattern. For a "expected" /// argument, it will be None. The vector is a list of (name, ty) /// strings for the components of the tuple. Tuple(Option<Span>, Vec<(String, String)>), } impl ArgKind { fn empty() -> ArgKind { ArgKind::Arg("_".to_owned(), "_".to_owned()) } /// Creates an `ArgKind` from the expected type of an /// argument. It has no name (`_`) and an optional source span. pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind { match t.kind() { ty::Tuple(tys) => ArgKind::Tuple( span, tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(), ), _ => ArgKind::Arg("_".to_owned(), t.to_string()), } } }
report_overflow_error_cycle
run_cleaning_cache.py
#!/usr/bin/env python3 import os import sys from vmaf.core.quality_runner import QualityRunner from vmaf.core.result_store import FileSystemResultStore from vmaf.routine import run_remove_results_for_dataset from vmaf.tools.misc import import_python_file __copyright__ = "Copyright 2016-2020, Netflix, Inc." __license__ = "BSD+Patent" def print_usage(): quality_runner_types = ['VMAF', 'PSNR', 'SSIM', 'MS_SSIM'] print("usage: " + os.path.basename(sys.argv[0]) + \ " quality_type dataset_filepath\n") print("quality_type:\n\t" + "\n\t".join(quality_runner_types) +"\n") def main():
if __name__ == '__main__': ret = main() exit(ret)
if len(sys.argv) < 3: print_usage() return 2 try: quality_type = sys.argv[1] dataset_filepath = sys.argv[2] except ValueError: print_usage() return 2 try: dataset = import_python_file(dataset_filepath) except Exception as e: print("Error: " + str(e)) return 1 try: runner_class = QualityRunner.find_subclass(quality_type) except: print_usage() return 2 result_store = FileSystemResultStore() run_remove_results_for_dataset(result_store, dataset, runner_class) return 0
utils.js
//https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript export function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, "\\$&"); var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(url); if (!results) return null;
return decodeURIComponent(results[2].replace(/\+/g, " ")); }
if (!results[2]) return '';
transforms.py
""" Transforms of aocd raw input text to something more useful for speed-solving. Every function here needs to accept one positional argument and return the 'massaged' data. """ __all__ = ["lines", "numbers"] def lines(data):
def numbers(data): return [int(n) for n in data.splitlines()]
return data.splitlines()
sorting.py
''' Sorting Examples for showcasing and developing Jungle features ''' import inspect from jungle import JungleExperiment, JungleProfiler import numpy as np print('Finished Loading Modules') class Sorting_Prototype: print('\n---Test Sort N---') @JungleExperiment(reps=1, n=[100, 500]) def test_sort_n(self, n=100, seed=1234): ''' Test sorting an iterable of size n with a random distribution ''' # make data to sort with random distribution np.random.seed(seed) list_2_sort = list(np.random.randn(n)) @JungleProfiler() def sort_n(l): sorted_list = self.sort(l) return sorted_list # Sort and check sort status sorted_list, _ = sort_n(list_2_sort) sort_status = all(sorted_list[i] <= sorted_list[i + 1] for i in range(len(sorted_list) - 1)) return sort_status print('\n---Test Block Sort---') @JungleExperiment(reps=1, n_blocks=[2, 4], block_size=[50, 100]) @JungleProfiler() def test_block_random_sort(self, n_blocks=4, block_size=100):
class NP_QuickSort(Sorting_Prototype): def sort(self, l): return np.sort(l, kind='quicksort') class NP_MergeSort(Sorting_Prototype): def sort(self, l): return np.sort(l, kind='mergesort') class NP_HeapSort(Sorting_Prototype): def sort(self, l): return np.sort(l, kind='heapsort') if __name__ == '__main__': print('\n__main__\n') print('\n---Starting Call #1---') m1 = NP_QuickSort() jc1 = m1.test_sort_n() print('\n---Starting Call #2---') m2 = NP_MergeSort() jc2 = m2.test_sort_n() print('\n---Starting Call #3---') m1 = NP_QuickSort() jc1 = m1.test_block_random_sort() print('\n---Starting Call #4---') m2 = NP_MergeSort() jc2 = m2.test_block_random_sort()
print('n_blocks: %s' % n_blocks) print('block_size: %s' % block_size) return 'something'
allocator.go
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package value // Allocator provides a value object allocation strategy. // Value objects can be allocated by passing an allocator to the "Using" // receiver functions on the value interfaces, e.g. Map.ZipUsing(allocator, ...). // Value objects returned from "Using" functions should be given back to the allocator // once longer needed by calling Allocator.Free(Value). type Allocator interface { // Free gives the allocator back any value objects returned by the "Using" // receiver functions on the value interfaces. // interface{} may be any of: Value, Map, List or Range. Free(interface{}) // The unexported functions are for "Using" receiver functions of the value types // to request what they need from the allocator. allocValueUnstructured() *valueUnstructured allocListUnstructuredRange() *listUnstructuredRange allocValueReflect() *valueReflect allocMapReflect() *mapReflect allocStructReflect() *structReflect allocListReflect() *listReflect allocListReflectRange() *listReflectRange } // HeapAllocator simply allocates objects to the heap. It is the default // allocator used receiver functions on the value interfaces that do not accept // an allocator and should be used whenever allocating objects that will not // be given back to an allocator by calling Allocator.Free(Value). var HeapAllocator = &heapAllocator{} type heapAllocator struct{} func (p *heapAllocator) allocValueUnstructured() *valueUnstructured { return &valueUnstructured{} } func (p *heapAllocator) allocListUnstructuredRange() *listUnstructuredRange { return &listUnstructuredRange{vv: &valueUnstructured{}} } func (p *heapAllocator) allocValueReflect() *valueReflect { return &valueReflect{} } func (p *heapAllocator) allocStructReflect() *structReflect { return &structReflect{} } func (p *heapAllocator) allocMapReflect() *mapReflect { return &mapReflect{} } func (p *heapAllocator) allocListReflect() *listReflect { return &listReflect{} } func (p *heapAllocator) allocListReflectRange() *listReflectRange { return &listReflectRange{vr: &valueReflect{}} } func (p *heapAllocator) Free(_ interface{}) {} // NewFreelistAllocator creates freelist based allocator. // This allocator provides fast allocation and freeing of short lived value objects. // // The freelists are bounded in size by freelistMaxSize. If more than this amount of value objects is // allocated at once, the excess will be returned to the heap for garbage collection when freed. // // This allocator is unsafe and must not be accessed concurrently by goroutines. // // This allocator works well for traversal of value data trees. Typical usage is to acquire // a freelist at the beginning of the traversal and use it through out // for all temporary value access. func NewFreelistAllocator() Allocator
// Bound memory usage of freelists. This prevents the processing of very large lists from leaking memory. // This limit is large enough for endpoints objects containing 1000 IP address entries. Freed objects // that don't fit into the freelist are orphaned on the heap to be garbage collected. const freelistMaxSize = 1000 type freelistAllocator struct { valueUnstructured *freelist listUnstructuredRange *freelist valueReflect *freelist mapReflect *freelist structReflect *freelist listReflect *freelist listReflectRange *freelist } type freelist struct { list []interface{} new func() interface{} } func (f *freelist) allocate() interface{} { var w2 interface{} if n := len(f.list); n > 0 { w2, f.list = f.list[n-1], f.list[:n-1] } else { w2 = f.new() } return w2 } func (f *freelist) free(v interface{}) { if len(f.list) < freelistMaxSize { f.list = append(f.list, v) } } func (w *freelistAllocator) Free(value interface{}) { switch v := value.(type) { case *valueUnstructured: v.Value = nil // don't hold references to unstructured objects w.valueUnstructured.free(v) case *listUnstructuredRange: v.vv.Value = nil // don't hold references to unstructured objects w.listUnstructuredRange.free(v) case *valueReflect: v.ParentMapKey = nil v.ParentMap = nil w.valueReflect.free(v) case *mapReflect: w.mapReflect.free(v) case *structReflect: w.structReflect.free(v) case *listReflect: w.listReflect.free(v) case *listReflectRange: v.vr.ParentMapKey = nil v.vr.ParentMap = nil w.listReflectRange.free(v) } } func (w *freelistAllocator) allocValueUnstructured() *valueUnstructured { return w.valueUnstructured.allocate().(*valueUnstructured) } func (w *freelistAllocator) allocListUnstructuredRange() *listUnstructuredRange { return w.listUnstructuredRange.allocate().(*listUnstructuredRange) } func (w *freelistAllocator) allocValueReflect() *valueReflect { return w.valueReflect.allocate().(*valueReflect) } func (w *freelistAllocator) allocStructReflect() *structReflect { return w.structReflect.allocate().(*structReflect) } func (w *freelistAllocator) allocMapReflect() *mapReflect { return w.mapReflect.allocate().(*mapReflect) } func (w *freelistAllocator) allocListReflect() *listReflect { return w.listReflect.allocate().(*listReflect) } func (w *freelistAllocator) allocListReflectRange() *listReflectRange { return w.listReflectRange.allocate().(*listReflectRange) }
{ return &freelistAllocator{ valueUnstructured: &freelist{new: func() interface{} { return &valueUnstructured{} }}, listUnstructuredRange: &freelist{new: func() interface{} { return &listUnstructuredRange{vv: &valueUnstructured{}} }}, valueReflect: &freelist{new: func() interface{} { return &valueReflect{} }}, mapReflect: &freelist{new: func() interface{} { return &mapReflect{} }}, structReflect: &freelist{new: func() interface{} { return &structReflect{} }}, listReflect: &freelist{new: func() interface{} { return &listReflect{} }}, listReflectRange: &freelist{new: func() interface{} { return &listReflectRange{vr: &valueReflect{}} }}, } }
account.rs
//! Endpoints for account registration and management. pub mod add_3pid; pub mod bind_3pid; pub mod change_password; pub mod deactivate; pub mod delete_3pid; pub mod get_username_availability; pub mod register; pub mod request_3pid_management_token_via_email; pub mod request_3pid_management_token_via_msisdn; pub mod request_openid_token; pub mod request_password_change_token_via_email; pub mod request_password_change_token_via_msisdn; pub mod request_registration_token_via_email; pub mod request_registration_token_via_msisdn; pub mod unbind_3pid; pub mod whoami; use ruma_common::Outgoing; use serde::{Deserialize, Serialize}; /// Additional authentication information for requestToken endpoints. #[derive(Clone, Debug, Outgoing, Serialize)] #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)] pub struct IdentityServerInfo<'a> { /// The ID server to send the onward request to as a hostname with an /// appended colon and port number if the port is not the default. pub id_server: &'a str, /// Access token previously registered with identity server. pub id_access_token: &'a str, } impl<'a> IdentityServerInfo<'a> { /// Creates a new `IdentityServerInfo` with the given server name and access token. pub fn new(id_server: &'a str, id_access_token: &'a str) -> Self { Self { id_server, id_access_token } } } /// Possible values for deleting or unbinding 3PIDs #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub enum
{ /// Either the homeserver couldn't determine the right identity server to contact, or the /// identity server refused the operation. NoSupport, /// Success. Success, }
ThirdPartyIdRemovalStatus
DependMap.ts
import {getCallState} from '../../../../../main/common/rx/depend/core/CallState' import {depend} from '../../../../../main/common/rx/depend/core/depend' import {DependMap} from '../../../../../main/common/rx/depend/lists/DependMap' import {assert} from '../../../../../main/common/test/Assert' import {describe, it} from '../../../../../main/common/test/Mocha' import {clearCallStates} from '../rx/depend/src/helpers' declare const after describe('common > main > lists > DependMap', function() { this.timeout(20000) it('base', function() { const map = new DependMap() assert.notOk(getCallState(map.dependAll).call(map)) assert.notOk(getCallState(map.dependAnyKey).call(map)) assert.notOk(getCallState(map.dependAnyValue).call(map))
assert.strictEqual(map.get(1), 2) assert.strictEqual(map.get(2), void 0) assert.deepStrictEqual(Array.from(map.entries()), [[1, 2]]) assert.deepStrictEqual(Array.from(map.keys()), [1]) assert.deepStrictEqual(Array.from(map.values()), [2]) map.clear() assert.strictEqual(map.get(1), void 0) assert.notOk(getCallState(map.dependAll).call(map)) assert.notOk(getCallState(map.dependAnyKey).call(map)) assert.notOk(getCallState(map.dependAnyValue).call(map)) depend(() => { assert.strictEqual(map.size, 0) })() assert.ok(getCallState(map.dependAll).call(map)) assert.ok(getCallState(map.dependAnyKey).call(map)) assert.notOk(getCallState(map.dependAnyValue).call(map)) depend(() => { map.set(1, 2) })() assert.ok(getCallState(map.dependAll).call(map)) assert.ok(getCallState(map.dependAnyKey).call(map)) assert.notOk(getCallState(map.dependValue).call(map, 2)) assert.notOk(getCallState(map.dependAnyValue).call(map)) depend(() => { assert.strictEqual(map.get(2), void 0) })() assert.ok(getCallState(map.dependAll).call(map)) assert.ok(getCallState(map.dependAnyKey).call(map)) assert.ok(getCallState(map.dependValue).call(map, 2)) assert.notOk(getCallState(map.dependAnyValue).call(map)) depend(() => { assert.deepStrictEqual(Array.from(map.entries()), [[1, 2]]) })() assert.ok(getCallState(map.dependAll).call(map)) assert.ok(getCallState(map.dependAnyKey).call(map)) assert.ok(getCallState(map.dependValue).call(map, 2)) assert.ok(getCallState(map.dependAnyValue).call(map)) clearCallStates() }) })
assert.strictEqual(map.size, 0) map.set(1, 2)
nft-transaction.service.js
import { COLLECTIONS } from '../common/constants'; export default class
{ constructor(_db) { this.db = _db; } /** * This function add record in nft_transaction tables. * @param {Object} data * data = { * tokenUri, * tokenId, * shieldcontractAddress, * transactionType, * sender: { * name, * address, * }, * receiver: { * name, * address, * } * } */ insertTransaction(data) { return this.db.saveData(COLLECTIONS.NFT_TRANSACTION, data); } /** * This function fetch ERC-721 (nft) transactions * from nft_transction collection * @param {object} query */ getTransactions(query) { const { pageNo, limit } = query; return this.db.getDbData( COLLECTIONS.NFT_TRANSACTION, {}, undefined, { createdAt: -1 }, parseInt(pageNo, 10), parseInt(limit, 10), ); } }
NftTransactionService
Backdrop.tsx
import { styled } from 'twin.macro' import { appear } from '../../theme' export default styled.div` position: fixed;
background: rgba(0, 0, 0, 0.65); animation: ${appear} 0.5s linear; `
top: 0; left: 0; height: 100vh; width: 100%;
artists.py
import csv import requests import socket from bs4 import BeautifulSoup import re import json def parse_artists(): artist_profiles = [] try: url = 'http://wx.toronto.ca/inter/pmmd/streetart.nsf/artists?OpenView' response = requests.get(url) html = response.content soup = BeautifulSoup(html) link_list = soup.findAll('a', attrs={'class': 'viewa1'}) for item in link_list: item_url = 'http://wx.toronto.ca'+item.get('href') profile = get_profile_data(item_url) artist_profiles.append(profile) except Exception as e: print (e.message) return artist_profiles def
(url): try: response = requests.get(url) html = response.content soup = BeautifulSoup(html) profile = soup.find('div', attrs={'id': 'profiledisplay'}).text name = soup.findAll('legend')[0].text email = re.search(r'[\w\.-]+@[\w\.-]+', profile).group().replace('Business', '') website = re.search(r'Website: (.*?)[\n\r\s]+', profile).group().replace('Website: ', '') bio = re.search(r'Profile\n(.*?)\n', profile).group().replace('Profile', '') description = re.search(r'Business/Organization Description\n(.*?)\n', profile).group().replace('Business/Organization Description', '') experience = re.search(r'Experience\n(.*?)\n', profile).group().replace('Experience', '') return { "name": name, "email": email, "website": website, "bio": bio, "description": description, "experience": experience, "dateJoined": "1508884475917", "dateUpdated": "1508884475917" } return profile except Exception as e: print (e.message) return with open('artists.json', 'w') as outfile: json.dump(parse_artists(), outfile) '''artist_urls = get_artist_urls() artist_array = compile_artist_profiles(artist_urls) outfile = open("./toronto-artists.csv", "wb") writer = csv.writer(outfile) writer.writerows(recipe_array)'''
get_profile_data
member.rs
//! Member expression parsing. //! //! More information: //! - [ECMAScript specification][spec] //! //! [spec]: https://tc39.es/ecma262/#prod-MemberExpression use super::arguments::Arguments; use crate::{ syntax::{ ast::{ node::{ field::{GetConstField, GetField}, Call, New, Node, }, Keyword, Punctuator, }, lexer::TokenKind, parser::{ expression::{primary::PrimaryExpression, Expression}, AllowAwait, AllowYield, Cursor, ParseError, ParseResult, TokenParser, }, }, BoaProfiler, }; use std::io::Read; /// Parses a member expression. /// /// More information: /// - [ECMAScript specification][spec] /// /// [spec]: https://tc39.es/ecma262/#prod-MemberExpression #[derive(Debug, Clone, Copy)] pub(super) struct MemberExpression { allow_yield: AllowYield, allow_await: AllowAwait, } impl MemberExpression { /// Creates a new `MemberExpression` parser. pub(super) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self where Y: Into<AllowYield>, A: Into<AllowAwait>, { Self { allow_yield: allow_yield.into(), allow_await: allow_await.into(), } } } impl<R> TokenParser<R> for MemberExpression where R: Read, { type Output = Node; fn parse(self, cursor: &mut Cursor<R>) -> ParseResult { let _timer = BoaProfiler::global().start_event("MemberExpression", "Parsing"); let mut lhs = if cursor.peek(0)?.ok_or(ParseError::AbruptEnd)?.kind() == &TokenKind::Keyword(Keyword::New) { let _ = cursor.next().expect("new keyword disappeared"); let lhs = self.parse(cursor)?; let args = Arguments::new(self.allow_yield, self.allow_await).parse(cursor)?; let call_node = Call::new(lhs, args); Node::from(New::from(call_node)) } else { PrimaryExpression::new(self.allow_yield, self.allow_await).parse(cursor)? }; while let Some(tok) = cursor.peek(0)? { match tok.kind() { TokenKind::Punctuator(Punctuator::Dot) => { cursor.next()?.expect("dot punctuator token disappeared"); // We move the parser forward.
match token.kind() { TokenKind::Identifier(name) => { lhs = GetConstField::new(lhs, name.clone()).into() } TokenKind::Keyword(kw) => { lhs = GetConstField::new(lhs, kw.to_string()).into() } _ => { return Err(ParseError::expected( vec![TokenKind::identifier("identifier")], token, "member expression", )); } } } TokenKind::Punctuator(Punctuator::OpenBracket) => { cursor .next()? .expect("open bracket punctuator token disappeared"); // We move the parser forward. let idx = Expression::new(true, self.allow_yield, self.allow_await).parse(cursor)?; cursor.expect(Punctuator::CloseBracket, "member expression")?; lhs = GetField::new(lhs, idx).into(); } _ => break, } } Ok(lhs) } }
let token = cursor.next()?.ok_or(ParseError::AbruptEnd)?;
format.js
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); /*! * devextreme-angular * Version: 18.2.5 * Build date: Wed Jan 23 2019 * * Copyright (c) 2012 - 2019 Developer Express Inc. ALL RIGHTS RESERVED * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file in the root of the project for details. * * https://github.com/DevExpress/devextreme-angular */ Object.defineProperty(exports, "__esModule", { value: true }); var nested_option_1 = require("../../../core/nested-option"); var DxoFormat = (function (_super) { __extends(DxoFormat, _super); function
() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(DxoFormat.prototype, "currency", { get: function () { return this._getOption('currency'); }, set: function (value) { this._setOption('currency', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoFormat.prototype, "formatter", { get: function () { return this._getOption('formatter'); }, set: function (value) { this._setOption('formatter', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoFormat.prototype, "parser", { get: function () { return this._getOption('parser'); }, set: function (value) { this._setOption('parser', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoFormat.prototype, "precision", { get: function () { return this._getOption('precision'); }, set: function (value) { this._setOption('precision', value); }, enumerable: true, configurable: true }); Object.defineProperty(DxoFormat.prototype, "type", { get: function () { return this._getOption('type'); }, set: function (value) { this._setOption('type', value); }, enumerable: true, configurable: true }); return DxoFormat; }(nested_option_1.NestedOption)); exports.DxoFormat = DxoFormat; //# sourceMappingURL=format.js.map
DxoFormat
gender_discrimination.py
# pandas standard library import sys # third-party import pandas import matplotlib import matplotlib.pyplot as plot matplotlib.style.use('ggplot') GENDER_COUNT = 24 MALES_PROMOTED = 21 FEMALES_PROMOTED = 14 GENDER_DIFFERENCE = MALES_PROMOTED - FEMALES_PROMOTED FEMALES_NOT_PROMOTED = GENDER_COUNT - FEMALES_PROMOTED MALES_NOT_PROMOTED = GENDER_COUNT - MALES_PROMOTED experiment_data = pandas.DataFrame({"Promoted": [MALES_PROMOTED, FEMALES_PROMOTED], "Not Promoted": [MALES_NOT_PROMOTED, FEMALES_NOT_PROMOTED]}, index='male female'.split(), columns=["Promoted", "Not Promoted"]) experiment_frame = experiment_data.copy() experiment_frame['Total'] = sum((experiment_frame[column] for column in experiment_frame.columns)) last_row = pandas.DataFrame(experiment_frame.sum()).transpose() last_row.index = pandas.Index(['Total']) experiment_frame = pandas.concat((experiment_frame, last_row)) class IndentOutput(object):
print('.. csv-table:: Experiment Outcome') print(' :header: ,{0}\n'.format(','.join(experiment_frame.columns))) experiment_frame.to_csv(IndentOutput, header=False) print('.. csv-table:: Experiment proportions') print(' :header: ,{0}\n'.format(','.join(experiment_frame.columns))) totals = pandas.Series([GENDER_COUNT, GENDER_COUNT, GENDER_COUNT * 2], index='male female Total'.split()) total_frame = pandas.DataFrame({'Promoted': totals, "Not Promoted": totals, "Total": totals}) proportions = experiment_frame/total_frame proportions.to_csv(IndentOutput, header=False, columns=['Promoted', 'Not Promoted', 'Total'], float_format="%.3f") path = 'figures/gender_experiment_bar.svg' figure = plot.figure() axe = figure.gca() experiment_data.plot(kind='bar', ax=axe) figure.savefig(path) print('.. image:: {0}'.format(path)) print(" \\frac{{{0}}}{{{2}}}- \\frac{{{1}}}{{{2}}}&=\\frac{{{3}}}{{{2}}}\\\\".format(MALES_PROMOTED, FEMALES_PROMOTED, GENDER_COUNT, GENDER_DIFFERENCE)) print(" &\\approx {:.3f}\\\\".format(GENDER_DIFFERENCE/GENDER_COUNT))
"""Fake file output for csv-writing """ @classmethod def write(cls, line): """Write line to stdout with three spaces prepended""" sys.stdout.write(" {0}".format(line))
core.go
// Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package proto import ( "bytes" "fmt" "reflect" "strconv" "time" "github.com/hazelcast/hazelcast-go-client/core" "github.com/hazelcast/hazelcast-go-client/internal/proto/bufutil" "github.com/hazelcast/hazelcast-go-client/internal/util/timeutil" "github.com/hazelcast/hazelcast-go-client/serialization" ) type Address struct { host string port int } func NewAddressWithParameters(Host string, Port int) *Address { return &Address{Host, Port} } func (a *Address) Host() string { return a.host } func (a *Address) Port() int { return int(a.port) } func (a *Address) String() string { return a.Host() + ":" + strconv.Itoa(a.Port()) } type uuid struct { msb int64 lsb int64 } type Member struct { address Address uuid string isLiteMember bool attributes map[string]string } func NewMember(address Address, uuid string, isLiteMember bool, attributes map[string]string) *Member { return &Member{address: address, uuid: uuid, isLiteMember: isLiteMember, attributes: attributes} } func (m *Member) Address() core.Address { return &m.address } func (m *Member) UUID() string { return m.uuid } func (m *Member) IsLiteMember() bool { return m.isLiteMember } func (m *Member) Attributes() map[string]string { return m.attributes } func (m *Member) String() string { memberInfo := fmt.Sprintf("Member %s - %s", &m.address, m.UUID()) if m.IsLiteMember() { memberInfo += " lite" } return memberInfo } func (m *Member) HasSameAddress(member *Member) bool { return m.address == member.address } type Pair struct { key, value interface{} } func NewPair(key interface{}, value interface{}) *Pair { return &Pair{key, value} } func (p *Pair) Key() interface{} { return p.key } func (p *Pair) Value() interface{} { return p.value } func (m *Member) Equal(member2 Member) bool { if m.address != member2.address { return false } if m.uuid != member2.uuid { return false } if m.isLiteMember != member2.isLiteMember { return false } if !reflect.DeepEqual(m.attributes, member2.attributes) { return false } return true } type MemberAttributeEvent struct { operationType int32 key string value string member core.Member } func
(operationType int32, key string, value string, member core.Member) *MemberAttributeEvent { return &MemberAttributeEvent{ operationType: operationType, key: key, value: value, member: member, } } func (m *MemberAttributeEvent) OperationType() int32 { return m.operationType } func (m *MemberAttributeEvent) Key() string { return m.key } func (m *MemberAttributeEvent) Value() string { return m.value } func (m *MemberAttributeEvent) Member() core.Member { return m.member } type DistributedObjectInfo struct { name string serviceName string } func (i *DistributedObjectInfo) Name() string { return i.name } func (i *DistributedObjectInfo) ServiceName() string { return i.serviceName } type DataEntryView struct { keyData serialization.Data valueData serialization.Data cost int64 creationTime int64 expirationTime int64 hits int64 lastAccessTime int64 lastStoredTime int64 lastUpdateTime int64 version int64 evictionCriteriaNumber int64 ttl int64 } func (ev *DataEntryView) KeyData() serialization.Data { return ev.keyData } func (ev *DataEntryView) ValueData() serialization.Data { return ev.valueData } func (ev *DataEntryView) Cost() int64 { return ev.cost } func (ev *DataEntryView) CreationTime() int64 { return ev.creationTime } func (ev *DataEntryView) ExpirationTime() int64 { return ev.expirationTime } func (ev *DataEntryView) Hits() int64 { return ev.hits } func (ev *DataEntryView) LastAccessTime() int64 { return ev.lastAccessTime } func (ev *DataEntryView) LastStoredTime() int64 { return ev.lastStoredTime } func (ev *DataEntryView) LastUpdateTime() int64 { return ev.lastUpdateTime } func (ev *DataEntryView) Version() int64 { return ev.version } func (ev *DataEntryView) EvictionCriteriaNumber() int64 { return ev.evictionCriteriaNumber } func (ev *DataEntryView) TTL() int64 { return ev.ttl } type EntryView struct { key interface{} value interface{} cost int64 creationTime time.Time expirationTime time.Time hits int64 lastAccessTime time.Time lastStoredTime time.Time lastUpdateTime time.Time version int64 evictionCriteriaNumber int64 ttl time.Duration } func NewEntryView(key interface{}, value interface{}, cost int64, creationTime int64, expirationTime int64, hits int64, lastAccessTime int64, lastStoredTime int64, lastUpdateTime int64, version int64, evictionCriteriaNumber int64, ttl int64) *EntryView { return &EntryView{ key: key, value: value, cost: cost, creationTime: timeutil.ConvertMillisToUnixTime(creationTime), expirationTime: timeutil.ConvertMillisToUnixTime(expirationTime), hits: hits, lastAccessTime: timeutil.ConvertMillisToUnixTime(lastAccessTime), lastStoredTime: timeutil.ConvertMillisToUnixTime(lastStoredTime), lastUpdateTime: timeutil.ConvertMillisToUnixTime(lastUpdateTime), version: version, evictionCriteriaNumber: evictionCriteriaNumber, ttl: timeutil.ConvertMillisToDuration(ttl), } } func (ev *EntryView) Key() interface{} { return ev.key } func (ev *EntryView) Value() interface{} { return ev.value } func (ev *EntryView) Cost() int64 { return ev.cost } func (ev *EntryView) CreationTime() time.Time { return ev.creationTime } func (ev *EntryView) ExpirationTime() time.Time { return ev.expirationTime } func (ev *EntryView) Hits() int64 { return ev.hits } func (ev *EntryView) LastAccessTime() time.Time { return ev.lastAccessTime } func (ev *EntryView) LastStoredTime() time.Time { return ev.lastStoredTime } func (ev *EntryView) LastUpdateTime() time.Time { return ev.lastUpdateTime } func (ev *EntryView) Version() int64 { return ev.version } func (ev *EntryView) EvictionCriteriaNumber() int64 { return ev.evictionCriteriaNumber } func (ev *EntryView) TTL() time.Duration { return ev.ttl } func (ev DataEntryView) Equal(ev2 DataEntryView) bool { if !bytes.Equal(ev.keyData.Buffer(), ev2.keyData.Buffer()) || !bytes.Equal(ev.valueData.Buffer(), ev2.valueData.Buffer()) { return false } if ev.cost != ev2.cost || ev.creationTime != ev2.creationTime || ev.expirationTime != ev2.expirationTime || ev.hits != ev2.hits { return false } if ev.lastAccessTime != ev2.lastAccessTime || ev.lastStoredTime != ev2.lastStoredTime || ev.lastUpdateTime != ev2.lastUpdateTime { return false } if ev.version != ev2.version || ev.evictionCriteriaNumber != ev2.evictionCriteriaNumber || ev.ttl != ev2.ttl { return false } return true } type ServerError struct { errorCode int32 className string message string stackTrace []core.StackTraceElement causeErrorCode int32 causeClassName string } func (e *ServerError) Error() string { return e.message } func (e *ServerError) ErrorCode() int32 { return e.errorCode } func (e *ServerError) ClassName() string { return e.className } func (e *ServerError) Message() string { return e.message } func (e *ServerError) StackTrace() []core.StackTraceElement { stackTrace := make([]core.StackTraceElement, len(e.stackTrace)) for i, v := range e.stackTrace { stackTrace[i] = v } return stackTrace } func (e *ServerError) CauseErrorCode() int32 { return e.causeErrorCode } func (e *ServerError) CauseClassName() string { return e.causeClassName } type StackTraceElement struct { declaringClass string methodName string fileName string lineNumber int32 } func (e *StackTraceElement) DeclaringClass() string { return e.declaringClass } func (e *StackTraceElement) MethodName() string { return e.methodName } func (e *StackTraceElement) FileName() string { return e.fileName } func (e *StackTraceElement) LineNumber() int32 { return e.lineNumber } type AbstractMapEvent struct { name string member core.Member eventType int32 } func (e *AbstractMapEvent) Name() string { return e.name } func (e *AbstractMapEvent) Member() core.Member { return e.member } func (e *AbstractMapEvent) EventType() int32 { return e.eventType } func (e *AbstractMapEvent) String() string { return fmt.Sprintf("entryEventType = %d, member = %v, name = '%s'", e.eventType, e.member, e.name) } type EntryEvent struct { *AbstractMapEvent key interface{} value interface{} oldValue interface{} mergingValue interface{} } func NewEntryEvent(name string, member core.Member, eventType int32, key interface{}, value interface{}, oldValue interface{}, mergingValue interface{}) *EntryEvent { return &EntryEvent{ AbstractMapEvent: &AbstractMapEvent{name, member, eventType}, key: key, value: value, oldValue: oldValue, mergingValue: mergingValue, } } func (e *EntryEvent) Key() interface{} { return e.key } func (e *EntryEvent) Value() interface{} { return e.value } func (e *EntryEvent) OldValue() interface{} { return e.oldValue } func (e *EntryEvent) MergingValue() interface{} { return e.mergingValue } type MapEvent struct { *AbstractMapEvent numberOfAffectedEntries int32 } func NewMapEvent(name string, member core.Member, eventType int32, numberOfAffectedEntries int32) core.MapEvent { return &MapEvent{ AbstractMapEvent: &AbstractMapEvent{name, member, eventType}, numberOfAffectedEntries: numberOfAffectedEntries, } } func (e *MapEvent) NumberOfAffectedEntries() int32 { return e.numberOfAffectedEntries } func (e *MapEvent) String() string { return fmt.Sprintf("MapEvent{%s, numberOfAffectedEntries = %d}", e.AbstractMapEvent.String(), e.numberOfAffectedEntries) } type ItemEvent struct { name string item interface{} eventType int32 member core.Member } func NewItemEvent(name string, item interface{}, eventType int32, member core.Member) core.ItemEvent { return &ItemEvent{ name: name, item: item, eventType: eventType, member: member, } } func (e *ItemEvent) Name() string { return e.name } func (e *ItemEvent) Item() interface{} { return e.item } func (e *ItemEvent) EventType() int32 { return e.eventType } func (e *ItemEvent) Member() core.Member { return e.member } type DecodeListenerResponse func(message *ClientMessage) string type EncodeListenerRemoveRequest func(registrationID string) *ClientMessage // Helper function to get flags for listeners func GetMapListenerFlags(listener interface{}) (int32, error) { flags := int32(0) if _, ok := listener.(core.EntryAddedListener); ok { flags |= bufutil.EntryEventAdded } if _, ok := listener.(core.EntryLoadedListener); ok { flags |= bufutil.EntryEventLoaded } if _, ok := listener.(core.EntryRemovedListener); ok { flags |= bufutil.EntryEventRemoved } if _, ok := listener.(core.EntryUpdatedListener); ok { flags |= bufutil.EntryEventUpdated } if _, ok := listener.(core.EntryEvictedListener); ok { flags |= bufutil.EntryEventEvicted } if _, ok := listener.(core.MapEvictedListener); ok { flags |= bufutil.MapEventEvicted } if _, ok := listener.(core.MapClearedListener); ok { flags |= bufutil.MapEventCleared } if _, ok := listener.(core.EntryExpiredListener); ok { flags |= bufutil.EntryEventExpired } if _, ok := listener.(core.EntryMergedListener); ok { flags |= bufutil.EntryEventMerged } if flags == 0 { return 0, core.NewHazelcastIllegalArgumentError(fmt.Sprintf("not a supported listener type: %v", reflect.TypeOf(listener)), nil) } return flags, nil } type TopicMessage struct { messageObject interface{} publishTime time.Time publishingMember core.Member } func NewTopicMessage(messageObject interface{}, publishTime int64, publishingMember core.Member) *TopicMessage { return &TopicMessage{ messageObject: messageObject, publishTime: timeutil.ConvertMillisToUnixTime(publishTime), publishingMember: publishingMember, } } func (m *TopicMessage) MessageObject() interface{} { return m.messageObject } func (m *TopicMessage) PublishTime() time.Time { return m.publishTime } func (m *TopicMessage) PublishingMember() core.Member { return m.publishingMember }
NewMemberAttributeEvent
main.rs
extern "C" { fn foo_c() -> i32; } fn
() { println!("Fooo: {}", unsafe { foo_c() }); }
main
testutil.go
/* * Copyright 2018 Comcast Cable Communications Management, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Package testutil provides utilities for running Mockser as an HTTP server during unit testing package testutil import ( "net/http/httptest" "github.com/tricksterproxy/mockster/pkg/routes" ) // NewTestServer launches a Test Prometheus Server (for unit testing) func NewTestServer() *httptest.Server
{ return httptest.NewServer(routes.GetRouter()) }
CF3.py
############################################################################### # Version: 1.1 # Last modified on: 3 April, 2016 # Developers: Michael G. Epitropakis # email: m_(DOT)_epitropakis_(AT)_lancaster_(DOT)_ac_(DOT)_uk ############################################################################### from cfunction import * import numpy as np class CF3(CFunction): def __init__(self, dim): super(CF3, self).__init__(dim, 6) # Initialize data for composition self._CFunction__sigma_ = np.array( [1.0, 1.0, 2.0, 2.0, 2.0, 2.0] ) self._CFunction__bias_ = np.zeros( self._CFunction__nofunc_ ) self._CFunction__weight_ = np.zeros( self._CFunction__nofunc_ ) self._CFunction__lambda_ = np.array( [1.0/4.0, 1.0/10.0, 2.0, 1.0, 2.0, 5.0] ) # Lower/Upper Bounds self._CFunction__lbound_ = -5.0 * np.ones( dim ) self._CFunction__ubound_ = 5.0 * np.ones( dim ) # Load optima o = np.loadtxt('data/optima.dat') if o.shape[1] >= dim: self._CFunction__O_ = o[:self._CFunction__nofunc_, :dim] else: # randomly initialize self._CFunction__O_ = self._CFunction__lbound_ + (self._CFunction__ubound_ - self._CFunction__lbound_) * np.random.rand( (self._CFunction__nofunc_, dim) )
self._CFunction__load_rotmat(fname) else: # M_ Identity matrices # TODO: Generate dimension independent rotation matrices self._CFunction__M_ = [ np.eye(dim) ] * self._CFunction__nofunc_ # Initialize functions of the composition self._CFunction__function_ = {0:FEF8F2, 1:FEF8F2, 2:FWeierstrass, 3:FWeierstrass, 4:FGrienwank, 5:FGrienwank} # Calculate fmaxi self._CFunction__calculate_fmaxi() def evaluate(self, x): return self._CFunction__evaluate_inner_(x)
# Load M_: Rotation matrices if dim == 2 or dim == 3 or dim == 5 or dim == 10 or dim == 20: fname = "data/CF3_M_D" + str(dim) + ".dat"
localidadController.js
'use stritc' var Localidad = require('../models/localidad'); function agregar (req, res){ var parametros = req.body; var localidad = new Localidad(); localidad.nombre = parametros.nombre; localidad.provincia = parametros.provincia._id; Localidad.find({nombre: localidad.nombre, provincia: localidad.provincia}).exec((err, existe) => { if(err){ console.log("Error al verificar si existe la localidad."); }else{ console.log(existe); if(existe.length == 0){ localidad.save((err, localidadGuardada) => { if(err){ res.status(500).send({message: "Error al guardar la localidad"}); }else{ res.status(200).send({message: "Localidad guardada exitosamente.", localidad: localidadGuardada}); } }); }else{ res.status(409).send({message: "Esta localidad existe en esta provincia."}); } } }); } function editar (req, res){ var id = req.params.id; var parametros = req.body; Localidad.findByIdAndUpdate(id, parametros, (err, localidadEditada) => { if(err){ res.status(500).send({message: "Error al editar la localidad", _id: id}); }else{ res.status(200).send({message: "Exito al editar la localidad", localidad: localidadEditada}); } }); } function borrar (req, res){ var id = req.params.id; Localidad.findById(id, (err, localidadABorrar) => { if(err){ res.status(500).send({message: "Error al encontrar la localidad", _id: id}); } if(!localidadABorrar){ res.status(404).send({message: "Localidad no encontrado"}); }else{ localidadABorrar.remove(err => { if(err){ res.status(500).send({message: "Error al borrar la localidad", _id: id}); }else{ res.status(200).send({message: "Localidad borrada con éxito.", localidad: localidadABorrar}); } }); } }); } function listar (req, res){ var page = Number(req.query.page); var size = Number(req.query.size); var sort = req.query.sort; var query = {}; var options = { sort: { provincia: sort || 'desc' }, populate: 'provincia', lean: false, page: page || 1, limit: size || 30 }; Localidad.paginate(query, options, function(err, localidades) { if(err){ res.status(500).send({message: "Error al obtener las localidades"}); }else{ if(!localidades){ res.status(404).send({message: "No encontrado"}); }else{ res.status(200).send({localidades: localidades.docs}); } } }); } function buscarPorId (req, res){ var id = req.params.id; Localidad.findById(id, (err, localidad) => { if(err){ res.status(500).send({message: "Error al encontrar la localidad", _id: id}); }else{ if(!localidad){ res.status(404).send({message: "No encontrado"}); }else{ res.status(200).send({localidad: localidad}); } } }); } function buscarPorProvincia (req, res){ var provincia = req.params.provincia; Localidad.find({ provincia: provincia }) .sort('nombre') .populate({ path: 'provincia' }) .exec((err, localidades) => { if(err){ res.status(500).send({message: "Error del servidor"}); }else{ if(!localidades){ res.status(404).send({message: "Nota no encontrada"}); }else{ res.status(200).send({localidades: localidades}); } } }); } function b
(req, res){ var nombre = req.params.nombre; Localidad.find({nombre: nombre}).exec((err, localidad) => { if(err){ res.status(500).send({message: "Error al buscar la localidad"}); }else{ if(!localidad){ res.status(404).send({message: "No encontrado"}); }else{ res.status(200).send({localidad: localidad}); } } }); } function verificarDuplicado (nombre, provincia){ Localidad.find({nombre: nombre, provincia: provincia}).exec((err, localidad) => { if(err){ console.log("Error al verificar si existe la localidad"); }else{ if(!localidad){ existe = false; }else{ existe = true; } } }); } module.exports = { agregar, editar, borrar, listar, buscarPorId, buscarPorProvincia, buscarPorNombre }
uscarPorNombre
transaction_monitor.rs
// Copyright 2020, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use futures::{ future, stream::{Fuse, StreamExt}, FutureExt, }; use log::*; use std::{cmp, time::Duration}; use tari_comms::types::CommsPublicKey; use tari_core::base_node::StateMachineHandle; use tari_shutdown::ShutdownSignal; use tari_wallet::{ output_manager_service::{ handle::{OutputManagerEvent, OutputManagerEventReceiver, OutputManagerHandle}, protocols::txo_validation_protocol::TxoValidationType, }, transaction_service::{ handle::TransactionServiceHandle, tasks::start_transaction_validation_and_broadcast_protocols::start_transaction_validation_and_broadcast_protocols, }, types::ValidationRetryStrategy, }; use tokio::{task, time}; const LOG_TARGET: &str = "c::bn::transaction_protocols_and_utxo_validation"; /// Asynchronously start transaction protocols and TXO validation /// ## Parameters /// `state_machine` - A handle to the state machine /// `transaction_service_handle` - A handle to the transaction service /// `oms_handle` - A handle to the output manager service /// `base_node_query_timeout` - A time after which queries to the base node times out /// `base_node_public_key` - The base node's public key /// `interrupt_signal` - terminate this task if we receive an interrupt signal pub fn spawn_transaction_protocols_and_utxo_validation( state_machine: StateMachineHandle, transaction_service_handle: TransactionServiceHandle, oms_handle: OutputManagerHandle, base_node_query_timeout: Duration, base_node_public_key: CommsPublicKey, interrupt_signal: ShutdownSignal, ) { task::spawn(async move { let transaction_task_fut = start_transaction_protocols_and_txo_validation( state_machine, transaction_service_handle, oms_handle, base_node_query_timeout, base_node_public_key, ); futures::pin_mut!(transaction_task_fut); // Exit on shutdown future::select(transaction_task_fut, interrupt_signal).await; info!( target: LOG_TARGET, "transaction_protocols_and_utxo_validation shut down" ); }); } /// Asynchronously start transaction protocols and TXO validation /// ## Parameters /// `state_machine` - A handle to the state machine /// `transaction_service_handle` - A handle to the transaction service /// `oms_handle` - A handle to the output manager service /// `base_node_query_timeout` - A time after which queries to the base node times out /// `base_node_public_key` - The base node's public key async fn
( state_machine: StateMachineHandle, mut transaction_service_handle: TransactionServiceHandle, mut oms_handle: OutputManagerHandle, base_node_query_timeout: Duration, base_node_public_key: CommsPublicKey, ) { let mut status_watch = state_machine.get_status_info_watch(); debug!( target: LOG_TARGET, "Waiting for initial sync before performing TXO validation and restarting of broadcast and transaction \ protocols." ); loop { // Only start the transaction broadcast and TXO validation protocols once the local node is synced match status_watch.recv().await { // Status watch has closed None => break, // Still not bootstrapped, carry on waiting Some(s) if !s.bootstrapped => { continue; }, // Bootstrapped! _ => {}, }; debug!( target: LOG_TARGET, "Initial sync achieved, performing TXO validation and restarting protocols.", ); let _ = oms_handle .set_base_node_public_key(base_node_public_key.clone()) .await .map_err(|e| { error!( target: LOG_TARGET, "Problem with Output Manager Service setting the base node public key: {}", e ); e }); // The event monitoring timeout must not be aggressive, as the validation protocols use // 'base_node_query_timeout' internally let event_monitoring_timeout = Duration::from_secs(cmp::max(60, base_node_query_timeout.as_secs() * 3)); loop { trace!(target: LOG_TARGET, "Attempting TXO validation for Unspent Outputs.",); let _ = oms_handle .validate_txos(TxoValidationType::Unspent, ValidationRetryStrategy::UntilSuccess) .await .map_err(|e| { error!( target: LOG_TARGET, "Problem starting Unspent TXO validation protocols in the Output Manager Service: {}", e ); e }); if monitor_validation_protocol(event_monitoring_timeout, oms_handle.get_event_stream_fused()).await { break; } } loop { trace!(target: LOG_TARGET, "Attempting TXO validation for Invalid Outputs.",); let _ = oms_handle .validate_txos(TxoValidationType::Invalid, ValidationRetryStrategy::UntilSuccess) .await .map_err(|e| { error!( target: LOG_TARGET, "Problem starting Invalid TXO validation protocols in the Output Manager Service: {}", e ); e }); if monitor_validation_protocol(event_monitoring_timeout, oms_handle.get_event_stream_fused()).await { break; } } loop { trace!(target: LOG_TARGET, "Attempting TXO validation for Spent Outputs.",); let _ = oms_handle .validate_txos(TxoValidationType::Spent, ValidationRetryStrategy::UntilSuccess) .await .map_err(|e| { error!( target: LOG_TARGET, "Problem starting Spent TXO validation protocols in the Output Manager Service: {}", e ); e }); if monitor_validation_protocol(event_monitoring_timeout, oms_handle.get_event_stream_fused()).await { break; } } // We want to ensure transaction protocols only use a fully validated TXO set, thus delaying this until // after the prior validation trace!(target: LOG_TARGET, "Attempting restart of the broadcast protocols.",); let _ = start_transaction_validation_and_broadcast_protocols( transaction_service_handle.clone(), ValidationRetryStrategy::UntilSuccess, ) .await .map_err(|e| { error!( target: LOG_TARGET, "Problem restarting broadcast protocols in the Transaction Service: {}", e ); e }); trace!(target: LOG_TARGET, "Attempting restart of the transaction protocols.",); let _ = transaction_service_handle .restart_transaction_protocols() .await .map_err(|e| { error!( target: LOG_TARGET, "Problem restarting transaction negotiation protocols in the Transaction Service: {}", e ); e }); break; } debug!( target: LOG_TARGET, "TXO validation and restarting of broadcast and transaction protocols concluded." ); } /// Monitors the TXO validation protocol events /// /// ## Paramters /// `event_timeout` - A time after which waiting for the next event from the output manager service times out /// `event_stream` - The TXO validation protocol subscriber event stream /// /// ##Returns /// bool indicating success or failure async fn monitor_validation_protocol( event_timeout: Duration, mut event_stream: Fuse<OutputManagerEventReceiver>, ) -> bool { let mut success = false; loop { let mut delay = time::delay_for(event_timeout).fuse(); futures::select! { result = event_stream.select_next_some() => { match result { Ok(msg) => { match (*msg).clone() { // Restart the protocol if aborted (due to 'BaseNodeNotSynced') OutputManagerEvent::TxoValidationAborted(s,_) => { trace!( target: LOG_TARGET, "TXO validation event 'TxoValidationAborted' ({}), restarting after 30s.", s, ); // This event will happen if the base node came out of sync for some reason, thus wait a bit before restarting tokio::time::delay_for(Duration::from_secs(30)).await; break; }, // Restart the protocol if it fails OutputManagerEvent::TxoValidationFailure(s,_) => { trace!( target: LOG_TARGET, "TXO validation event 'TxoValidationFailure' ({}), restarting after 30s.", s, ); // This event will happen due to an unknown reason, thus wait a bit before restarting tokio::time::delay_for(Duration::from_secs(30)).await; break; }, // Exit upon success OutputManagerEvent::TxoValidationSuccess(s,_) => { trace!( target: LOG_TARGET, "TXO validation event 'TxoValidationSuccess' ({}), success.", s, ); success = true; break; }, // Wait for the next event if timed out (several can be attempted) OutputManagerEvent::TxoValidationTimedOut(s,_) => { trace!( target: LOG_TARGET, "TXO validation event 'TxoValidationTimedOut' ({}), waiting.", s, ); continue; } // Wait for the next event if delayed OutputManagerEvent::TxoValidationDelayed(s,_) => { trace!( target: LOG_TARGET, "TXO validation event 'TxoValidationDelayed' ({}), waiting.", s, ); continue; } // Wait for the next event upon an error OutputManagerEvent::Error(s) => { trace!( target: LOG_TARGET, "TXO validation event 'Error({})', waiting.", s, ); continue; }, } }, Err(_) => trace!( target: LOG_TARGET, "Lagging read on event stream", ), } }, // Restart the protocol if it timed out () = delay => { trace!( target: LOG_TARGET, "TXO validation protocol timed out, restarting.", ); break; }, } } success }
start_transaction_protocols_and_txo_validation
BiosSettingRef.py
"""This module contains the general information for BiosSettingRef ManagedObject.""" import sys, os from ...ucsmo import ManagedObject from ...ucscoremeta import UcsVersion, MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class BiosSettingRefConsts(): IS_DEFAULT_NO = "no" IS_DEFAULT_YES = "yes" IS_SUPPORTED_NO = "no" IS_SUPPORTED_YES = "yes" class BiosSettingRef(ManagedObject): """This is BiosSettingRef class.""" consts = BiosSettingRefConsts() naming_props = set([u'name']) mo_meta = MoMeta("BiosSettingRef", "biosSettingRef", "setting-ref-[name]", VersionMeta.Version131c, "InputOutput", 0x3f, [], [""], [u'biosParameterRef'], [], ["Get"]) prop_meta = { "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version131c, MoPropertyMeta.INTERNAL, 0x2, None, None, r"""((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}""", [], []), "constant_name": MoPropertyMeta("constant_name", "constantName", "string", VersionMeta.Version141i, MoPropertyMeta.READ_ONLY, None, None, None, r"""[\-\.:_a-zA-Z0-9]{0,16}""", [], []), "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, 0x4, 0, 256, None, [], []), "is_default": MoPropertyMeta("is_default", "isDefault", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, None, None, None, None, ["no", "yes"], []), "is_supported": MoPropertyMeta("is_supported", "isSupported", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, None, None, None, None, ["no", "yes"], []), "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version131c, MoPropertyMeta.NAMING, 0x8, None, None, r"""[ !#$%&\(\)\*\+,\-\./:;\?@\[\]_\{\|\}~a-zA-Z0-9]{1,256}""", [], []), "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version131c, MoPropertyMeta.READ_ONLY, 0x10, 0, 256, None, [], []), "sacl": MoPropertyMeta("sacl", "sacl", "string", VersionMeta.Version302a, MoPropertyMeta.READ_ONLY, None, None, None, r"""((none|del|mod|addchild|cascade),){0,4}(none|del|mod|addchild|cascade){0,1}""", [], []), "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version131c, MoPropertyMeta.READ_WRITE, 0x20, None, None, r"""((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}""", [], []), } prop_map = { "childAction": "child_action", "constantName": "constant_name", "dn": "dn", "isDefault": "is_default", "isSupported": "is_supported", "name": "name", "rn": "rn", "sacl": "sacl", "status": "status", } def __init__(self, parent_mo_or_dn, name, **kwargs):
self._dirty_mask = 0 self.name = name self.child_action = None self.constant_name = None self.is_default = None self.is_supported = None self.sacl = None self.status = None ManagedObject.__init__(self, "BiosSettingRef", parent_mo_or_dn, **kwargs)
sharded_spawn.py
from typing import Optional from pytorch_lightning.core.optimizer import is_lightning_optimizer from pytorch_lightning.plugins.training_type.ddp_spawn import DDPSpawnPlugin from pytorch_lightning.utilities import _FAIRSCALE_AVAILABLE, rank_zero_only if _FAIRSCALE_AVAILABLE: from fairscale.optim import OSS from pytorch_lightning.overrides.fairscale import LightningShardedDataParallel class DDPSpawnShardedPlugin(DDPSpawnPlugin): def configure_ddp(self): self._wrap_optimizers() self._model = LightningShardedDataParallel( self.model, sharded_optimizer=self.lightning_module.trainer.optimizers ) def _reinit_optimizers_with_oss(self): optimizers = self.lightning_module.trainer.optimizers for x, optimizer in enumerate(optimizers):
zero_optimizer = OSS(params=optimizer.param_groups, optim=optim_class, **optimizer.defaults) optimizers[x] = zero_optimizer del optimizer trainer = self.lightning_module.trainer trainer.optimizers = trainer.convert_to_lightning_optimizers(optimizers) def _wrap_optimizers(self): trainer = self.model.trainer if trainer.testing: return self._reinit_optimizers_with_oss() def optimizer_state(self, optimizer: 'OSS') -> Optional[dict]: if is_lightning_optimizer(optimizer): optimizer = optimizer._optimizer if isinstance(optimizer, OSS): optimizer.consolidate_state_dict() return self._optim_state_dict(optimizer) @rank_zero_only def _optim_state_dict(self, optimizer): """ Retrieves state dict only on rank 0, which contains the entire optimizer state after calling :meth:`consolidate_state_dict`. """ return optimizer.state_dict()
if is_lightning_optimizer(optimizer): optimizer = optimizer._optimizer if not isinstance(optimizer, OSS): optim_class = type(optimizer)
index.js
import React, {PureComponent} from 'react'; import {Card, Steps, List, Button, message, Row, Col, Modal, Tag, Input, Form, Divider, Badge, Alert} from 'antd'; import {connect} from 'dva'; import classNames from 'classnames'; import {fetchApiSync} from '../../../utils/rs/Fetch'; import {formatDate} from '../../../utils/utils'; import moment from 'moment'; import FxLayout from '../../../myComponents/Layout/'; import Component from '../../../utils/rs/Component'; import ConsoleTitle from '../../../myComponents/Fx/ConsoleTitle'; import StandardTable from '../../../myComponents/Table/Standard'; import StandardModal from '../../../myComponents/Modal/Standard'; import EditForm from '../../../myComponents/Form/Edit'; import StandardRangePicker from '../../../myComponents/Date/StandardRangePicker'; import LoadingService from '../../../utils/rs/LoadingService'; const Fragment = React.Fragment; const modelNameSpace = "recruit"; const TextArea = Input.TextArea; const FormItem=Form.Item; @connect(state => ({ [modelNameSpace]: state[modelNameSpace], loading: state.loading, })) @Component.Model(modelNameSpace) @Component.Role('oa_hr_recruit') @Component.Pagination({model: modelNameSpace}) @Form.create() export default class extends PureComponent { state = { modal: { visible: false, record: {}, index: -1, isAdd: false, } }; getList = (page) => { } renderModal() { const {modal: {visible, record = {}}} = this.state; const {name, mobile, email} = record; const {form: {getFieldDecorator}} = this.props; return ( <StandardModal visible={visible} title='编辑' width={600} onCancel={e => this.setState({modal: {visible: false}})} > <Form layout='vertical' className="ant-form-slim"> <Row gutter={24}> <Col span={8}> <FormItem label='姓名'> {getFieldDecorator('name', { rules: [ {required: true, message: '请输入姓名!', type: 'string'}, ], initialValue: name, })( <Input placeholder="请输入姓名!"/> )} </FormItem> </Col> <Col span={8}> <FormItem label='手机'> {getFieldDecorator('mobile', { rules: [ {required: true, message: '请输入手机号!', type: 'string'}, ], initialValue: mobile, })( <Input placeholder="请输入手机号!"/> )} </FormItem> </Col> <Col span={8}> <FormItem label='邮箱'> {getFieldDecorator('email', { initialValue: email, })( <Input /> )} </FormItem> </Col> </Row> <Row> <Col></Col> <Col></Col> <Col></Col> </Row> </Form> </StandardModal> ) } renderBody() { const columns = [ { title: '姓名', dataIndex: 'name', }, { title: '手机', dataIndex: 'mobile', }, { title: '邮箱', dataIndex: 'email', }, { title: '渠道', dataIndex: 'recruitChannel', }, { title: '面试岗位', dataIndex: 'position', }, { title: '预约面试时间', dataIndex: 'orderDate' } , { title: '是否已面试', dataIndex: 'isInterview', }, { title: '面试时间', dataIndex: 'interviewDate', }, { title: '复试人员', dataIndex: 'reexamineUserName', }, { title: '是否通过', dataIndex: 'isPass', }, { title: '具体理由', dataIndex: 'reason', }, { title: '分配小组', dataIndex: 'depID', }, { title: '入职日期', dataIndex: 'entryDate', }, { title: '入职情况跟进', dataIndex: 'entryCondition', }, { title: '性格测试结果', dataIndex: 'FPA', } ]; const {data: {list}, pageIndex,} = this.props[modelNameSpace]; const actions = [ { button: { type: 'primary', text: '登记', icon: 'plus', onClick:()=>{ this.setState({ modal:{ visible:true, isAdd:true, index:-1, record:{}, } }) } } } ] return ( <div> <StandardTable actions={actions} mode='simple'
columns={columns} /> </div> ) } render() { const {loading, pagination} = this.props; const {data: {total}, pageIndex,} = this.props[modelNameSpace]; const fxLayoutProps = { header: { title: '招聘登记列表', actions: [ { button: { type: 'primary', text: '刷新', icon: 'retweet', onClick: e => this.getList(), } } ] }, body: { center: this.renderBody(), loading: loading.effects[`${modelNameSpace}/get`], }, footer: { pagination: pagination({total, pageIndex}, this.getList), } } return ( <Fragment> <FxLayout {...fxLayoutProps}/> {this.state.modal.visible?this.renderModal():null} </Fragment> ) } }
tools={['export']} dataSource={list}
endpoints.go
// Code generated by smithy-go-codegen DO NOT EDIT. package acmpca import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" internalendpoints "github.com/aws/aws-sdk-go-v2/service/acmpca/internal/endpoints" "github.com/awslabs/smithy-go/middleware" smithyhttp "github.com/awslabs/smithy-go/transport/http" "net/url" ) // EndpointResolverOptions is the service endpoint resolver options type EndpointResolverOptions = internalendpoints.Options // EndpointResolver interface for resolving service endpoints. type EndpointResolver interface { ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) } var _ EndpointResolver = &internalendpoints.Resolver{} // NewDefaultEndpointResolver constructs a new service endpoint resolver func NewDefaultEndpointResolver() *internalendpoints.Resolver
// EndpointResolverFunc is a helper utility that wraps a function so it satisfies // the EndpointResolver interface. This is useful when you want to add additional // endpoint resolving logic, or stub out specific endpoints with custom values. type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { return fn(region, options) } func resolveDefaultEndpointConfiguration(o *Options) { if o.EndpointResolver != nil { return } o.EndpointResolver = NewDefaultEndpointResolver() } type ResolveEndpoint struct { Resolver EndpointResolver Options EndpointResolverOptions } func (*ResolveEndpoint) ID() string { return "ResolveEndpoint" } func (m *ResolveEndpoint) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { req, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) } if m.Resolver == nil { return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") } var endpoint aws.Endpoint endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), m.Options) if err != nil { return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) } req.URL, err = url.Parse(endpoint.URL) if err != nil { return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) } if len(awsmiddleware.GetSigningName(ctx)) == 0 { signingName := endpoint.SigningName if len(signingName) == 0 { signingName = "acm-pca" } ctx = awsmiddleware.SetSigningName(ctx, signingName) } ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) return next.HandleSerialize(ctx, in) } func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { return stack.Serialize.Insert(&ResolveEndpoint{ Resolver: o.EndpointResolver, Options: o.EndpointOptions, }, "OperationSerializer", middleware.Before) } func removeResolveEndpointMiddleware(stack *middleware.Stack) error { _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) return err } type wrappedEndpointResolver struct { awsResolver aws.EndpointResolver resolver EndpointResolver } func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { if w.awsResolver == nil { goto fallback } endpoint, err = w.awsResolver.ResolveEndpoint(ServiceID, region) if err == nil { return endpoint, nil } if nf := (&aws.EndpointNotFoundError{}); !errors.As(err, &nf) { return endpoint, err } fallback: if w.resolver == nil { return endpoint, fmt.Errorf("default endpoint resolver provided was nil") } return w.resolver.ResolveEndpoint(region, options) } // WithEndpointResolver returns an EndpointResolver that first delegates endpoint // resolution to the awsResolver. If awsResolver returns aws.EndpointNotFoundError // error, the resolver will use the the provided fallbackResolver for resolution. // awsResolver and fallbackResolver must not be nil func WithEndpointResolver(awsResolver aws.EndpointResolver, fallbackResolver EndpointResolver) EndpointResolver { return &wrappedEndpointResolver{ awsResolver: awsResolver, resolver: fallbackResolver, } }
{ return internalendpoints.New() }