Skip to content

tables

sc_crawler.tables #

Table definitions for vendors, regions, zones, and other cloud resources.

Classes:

Name Description
Country

Country and continent mapping.

ComplianceFramework

List of Compliance Frameworks, such as HIPAA or SOC 2 Type 1.

Vendor

Compute resource vendors, such as cloud and server providers.

VendorComplianceLink

List of known Compliance Frameworks paired with vendors.

Region

Regions of Vendors.

Zone

Availability zones of Regions.

Storage

Flexible storage options that can be attached to a Server.

Server

Server types.

ServerPrice

Server type prices per Region and Allocation method.

ServerDescription

Variable length, plain English descriptions of Server hardware specs, performance, cost-efficiency, and workflow fit.

StoragePrice

Flexible Storage prices in each Region.

Database

Managed database SKUs.

DatabasePrice

Managed database SKU prices per Region.

DatabaseStorage

Managed database storage products.

DatabaseStoragePrice

Managed database storage prices in each Region.

TrafficPrice

Extra Traffic prices in each Region.

Ipv4Price

Price of an IPv4 address in each Region.

Benchmark

Benchmark scenario definitions.

BenchmarkScore

Results of running Benchmark scenarios on Servers or managed Databases.

ArchiveRule

Rules archiving records that were replaced by another record or deliberately dropped.

Metadata

Key/value metadata table for database release information.

Functions:

Name Description
is_table

Checks if an object is a SQLModel table definition.

Attributes:

Name Type Description
tables List[SQLModel]

List of all SQLModel (table) models.

Country #

Bases: CountryBase

Country and continent mapping.

Attributes:

Name Type Description
country_id str

Country code by ISO 3166 alpha-2.

continent str

Continent name.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class Country(CountryBase, table=True):
    """Country and continent mapping."""

    vendors: List["Vendor"] = Relationship(back_populates="country")
    regions: List["Region"] = Relationship(back_populates="country")

ComplianceFramework #

Bases: ComplianceFrameworkBase

List of Compliance Frameworks, such as HIPAA or SOC 2 Type 1.

Attributes:

Name Type Description
compliance_framework_id str

Unique identifier.

name str

Human-friendly name.

abbreviation Optional[str]

Short abbreviation of the Framework name.

description Optional[str]

Description of the framework in a few paragraphs, outlining key features and characteristics for reference.

logo Optional[str]

Publicly accessible URL to the image of the Framework's logo.

homepage Optional[str]

Public homepage with more information on the Framework.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class ComplianceFramework(ComplianceFrameworkBase, table=True):
    """List of Compliance Frameworks, such as HIPAA or SOC 2 Type 1."""

    vendor_links: List["VendorComplianceLink"] = Relationship(
        back_populates="compliance_framework"
    )

Vendor #

Bases: VendorBase

Compute resource vendors, such as cloud and server providers.

Examples:

>>> from sc_crawler.tables import Vendor
>>> from sc_crawler.lookup import countries
>>> aws = Vendor(vendor_id='aws', name='Amazon Web Services', homepage='https://aws.amazon.com', country=countries["US"], founding_year=2002)
>>> aws
Vendor(vendor_id='aws'...
>>> from sc_crawler import vendors
>>> vendors.aws
Vendor(vendor_id='aws'...

Attributes:

Name Type Description
vendor_id str

Unique identifier.

name str

Human-friendly name.

logo Optional[str]

Publicly accessible URL to the image of the Vendor's logo.

homepage Optional[str]

Public homepage of the Vendor.

country_id str

Reference to the Country, where the Vendor's main headquarter is located.

state Optional[str]

Optional state/administrative area of the Vendor's location within the Country.

city Optional[str]

Optional city name of the Vendor's main location.

address_line Optional[str]

Optional address line of the Vendor's main location.

zip_code Optional[str]

Optional ZIP code of the Vendor's main location.

founding_year int

4-digit year when the public cloud service of the Vendor was launched.

status_page Optional[str]

Public status page of the Vendor.

stopped_server_charged Optional[bool]

If the Vendor charges for stopped servers. In case it depends on the instance type or different versions of stopped states, this field reports the worst case.

billing_increment_seconds Optional[int]

The smallest increment of time for which the Vendor bills for.

minimum_billing_seconds Optional[int]

The minimum amount of time for which the Vendor bills for. In case it depends on the instance type or other context, this field reports the worst case.

billing_comment Optional[str]

Comment on the Vendor's billing.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Methods:

Name Description
set_table_rows_inactive

Set this vendor's records to INACTIVE in a table.

set_table_rows_active

Set this vendor's records to ACTIVE in a table.

inventory_compliance_frameworks

Get the vendor's all compliance frameworks.

inventory_regions

Get the vendor's all regions.

inventory_zones

Get all the zones in the vendor's regions.

inventory_servers

Get the vendor's all server types.

inventory_server_prices

Get the current standard/ondemand/reserved prices of all server types.

inventory_server_prices_spot

Get the current spot prices of all server types.

inventory_storages

Get the vendor's all storage types.

inventory_storage_prices

Get the current prices of all storage types.

inventory_traffic_prices

Get the current prices of all traffic types.

inventory_ipv4_prices

Get the current prices of all IPv4 types.

inventory_databases

Get the vendor's all managed database types.

inventory_database_prices

Get the current prices of all managed database types.

inventory_database_storages

Get the vendor's all managed database storage products.

inventory_database_storage_prices

Get the current prices of all managed database storage products.

Source code in sc_crawler/tables.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
class Vendor(VendorBase, table=True):
    """Compute resource vendors, such as cloud and server providers.

    Examples:
        >>> from sc_crawler.tables import Vendor
        >>> from sc_crawler.lookup import countries
        >>> aws = Vendor(vendor_id='aws', name='Amazon Web Services', homepage='https://aws.amazon.com', country=countries["US"], founding_year=2002)
        >>> aws
        Vendor(vendor_id='aws'...
        >>> from sc_crawler import vendors
        >>> vendors.aws
        Vendor(vendor_id='aws'...
    """  # noqa: E501

    compliance_framework_links: List["VendorComplianceLink"] = Relationship(
        back_populates="vendor"
    )
    country: Country = Relationship(back_populates="vendors")
    regions: List["Region"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    zones: List["Zone"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    storages: List["Storage"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    servers: List["Server"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    server_prices: List["ServerPrice"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    traffic_prices: List["TrafficPrice"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    ipv4_prices: List["Ipv4Price"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    storage_prices: List["StoragePrice"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    databases: List["Database"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    database_prices: List["DatabasePrice"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    database_storages: List["DatabaseStorage"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    database_storage_prices: List["DatabaseStoragePrice"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )
    benchmark_scores: List["BenchmarkScore"] = Relationship(
        back_populates="vendor", sa_relationship_kwargs={"viewonly": True}
    )

    # private attributes
    _methods: Optional[ModuleType] = PrivateAttr(default=None)
    _session: Optional[Session] = PrivateAttr()
    _progress_tracker: Optional[VendorProgressTracker] = PrivateAttr(
        default=VoidProgressTracker()
    )

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # SQLModel does not validates pydantic typing,
        # only when writing to DB (much later in the process)
        if not self.vendor_id:
            raise ValueError("No vendor id provided")
        if not self.name:
            raise ValueError("No vendor name provided")
        if not self.homepage:
            raise ValueError("No vendor homepage provided")
        if not self.country:
            raise ValueError("No vendor country provided")

    def _get_methods(self):
        if not getattr(self, "_methods", None):
            vendor_module = ".".join(
                [
                    __name__.split(".", maxsplit=1)[0],
                    "vendors",
                    f"_{self.vendor_id}",
                ]
            )
            try:
                self._methods = import_module(vendor_module)
            except Exception as exc:
                raise NotImplementedError(
                    f"Unsupported '{self.vendor_id}' vendor: cannot import its module."
                ) from exc
            # make sure all required methods exist
            for method in [
                "inventory_compliance_frameworks",
                "inventory_regions",
                "inventory_zones",
                "inventory_servers",
                "inventory_server_prices",
                "inventory_server_prices_spot",
                "inventory_storages",
                "inventory_storage_prices",
                "inventory_databases",
                "inventory_database_prices",
                "inventory_database_storages",
                "inventory_database_storage_prices",
                "inventory_traffic_prices",
                "inventory_ipv4_prices",
            ]:
                if not hasattr(self._methods, method):
                    raise NotImplementedError(
                        f"Unsupported '{self.vendor_id}' vendor: missing '{method}' method."
                    )
        return self._methods

    @property
    def session(self):
        """The Session to use for merging dependent objects into the database."""
        try:
            return self._session
        except Exception:
            return None

    @session.setter
    def session(self, session: Session):
        self._session = session

    @session.deleter
    def session(self):
        self._session = None

    @property
    def progress_tracker(self):
        """The [sc_crawler.logger.VendorProgressTracker][] to use for updating progress bars."""
        return self._progress_tracker

    @progress_tracker.setter
    def progress_tracker(self, progress_tracker: VendorProgressTracker):
        self._progress_tracker = progress_tracker

    @progress_tracker.deleter
    def progress_tracker(self):
        self._progress_tracker = None

    @property
    def tasks(self):
        """Reexport progress_tracker.tasks for easier access."""
        return self._progress_tracker.tasks

    def log(self, message: str, level: int = logging.INFO):
        logger.log(level, self.name + ": " + message, stacklevel=2)

    def set_table_rows_inactive(self, model: str, *args) -> None:
        """Set this vendor's records to [INACTIVE][sc_crawler.table_fields.Status] in a table.

        Positional arguments can be used to pass further filters
        (besides the default model.vendor_id filter) referencing the
        model object with SQLModel syntax.

        Records marked as [ARCHIVED][sc_crawler.table_fields.Status] are kept as-is,
        just like the `PLANNED_FOR_RETIREMENT` and `RETIRED` servers and databases,
        so that these keep their status and retirement date when no longer returned
        by the vendor.

        Examples:
            >>> aws.set_table_rows_inactive(ServerPrice, ServerPrice.price < 10)  # doctest: +SKIP
        """
        if self.session:
            query = (
                update(model)
                .where(model.vendor_id == self.vendor_id)
                .where(
                    model.status.not_in(
                        [
                            Status.ARCHIVED,
                            Status.PLANNED_FOR_RETIREMENT,
                            Status.RETIRED,
                        ]
                    )
                )
            )
            for arg in args:
                query = query.where(arg)
            self.session.exec(query.values(status=Status.INACTIVE))

    def set_table_rows_active(self, model: str, *args) -> None:
        """Set this vendor's records to [ACTIVE][sc_crawler.table_fields.Status] in a table.

        Positional arguments can be used to pass further filters
        (besides the default model.vendor_id filter) referencing the
        model object with SQLModel syntax.

        Records marked as [ARCHIVED][sc_crawler.table_fields.Status] are kept as-is.

        Examples:
            >>> aws.set_table_rows_active(ServerPrice, ServerPrice.price < 10)  # doctest: +SKIP
        """
        if self.session:
            query = (
                update(model)
                .where(model.vendor_id == self.vendor_id)
                .where(model.status != Status.ARCHIVED)
            )
            for arg in args:
                query = query.where(arg)
            self.session.exec(query.values(status=Status.ACTIVE))

    def _inventory(self, table: ScModel, inventory: Callable):
        """Mark all rows in a table inactive, then insert new/updated items."""
        new_records = inventory(self)
        if new_records:
            self.set_table_rows_inactive(table)
            insert_items(table, new_records, self)

    def _inventory_price_rounding(
        self,
        table: ScModel,
        inventory: Callable,
        *filters,
        prefix: str = "",
    ):
        """Mark rows in a table inactive, then insert new/updated items with 4-digit price rounding.

        Args:
            table: The SQLModel table class to update.
            inventory: Callable that returns list of items to insert.
            *filters: Optional filter expressions to apply when marking rows inactive.
            prefix: Optional prefix for progress tracking.
        """
        new_records = inventory(self)
        if new_records:
            self.set_table_rows_inactive(table, *filters)
            for item in new_records:
                item["price"] = round(float(item["price"]), 4)
            insert_items(table, new_records, self, prefix=prefix)

    @log_start_end
    def inventory_compliance_frameworks(self):
        """Get the vendor's all compliance frameworks."""
        self._inventory(
            VendorComplianceLink, self._get_methods().inventory_compliance_frameworks
        )

    @log_start_end
    def inventory_regions(self):
        """Get the vendor's all regions."""
        self._inventory(Region, self._get_methods().inventory_regions)

    @log_start_end
    def inventory_zones(self):
        """Get all the zones in the vendor's regions."""
        self._inventory(Zone, self._get_methods().inventory_zones)

    @log_start_end
    def inventory_servers(self):
        """Get the vendor's all server types."""
        self.set_table_rows_inactive(Server)
        servers = self._get_methods().inventory_servers(self)
        # show progress bar while downloading
        self.progress_tracker.start_task(
            name="Downloading sc-inspector-data", total=None
        )
        inspector_data_path()
        self.progress_tracker.hide_task()
        # actual HW inspection
        for server in servers:
            server = inspect_update_server_dict(server)
        insert_items(Server, servers, self)
        benchmarks = []
        self.progress_tracker.start_task(
            name="Searching for server benchmark(s)", total=len(self.servers)
        )
        for server in self.servers:
            benchmarks += inspect_server_benchmarks(server)
            self.progress_tracker.advance_task()
        self.progress_tracker.hide_task()
        self.set_table_rows_inactive(
            BenchmarkScore,
            BenchmarkScore.vendor_id == self.vendor_id,
            BenchmarkScore.resource_type == ResourceType.SERVER,
        )
        insert_items(BenchmarkScore, benchmarks, self, prefix="server")
        self.progress_tracker.start_task(
            name="Downloading sc-navigator-descriptions", total=None
        )
        descriptions_data_path()
        self.progress_tracker.hide_task()
        descriptions = []
        self.progress_tracker.start_task(
            name="Loading server description(s)", total=len(self.servers)
        )
        for server in self.servers:
            description = ingest_server_description(server)
            if description is not None:
                descriptions.append(description)
            self.progress_tracker.advance_task()
        self.progress_tracker.hide_task()
        self.set_table_rows_inactive(
            ServerDescription, ServerDescription.vendor_id == self.vendor_id
        )
        insert_items(ServerDescription, descriptions, self)

    @log_start_end
    def inventory_server_prices(self):
        """Get the current standard/ondemand/reserved prices of all server types."""
        self._inventory_price_rounding(
            ServerPrice,
            self._get_methods().inventory_server_prices,
            ServerPrice.allocation == Allocation.ONDEMAND,
            prefix="ondemand",
        )

    @log_start_end
    def inventory_server_prices_spot(self):
        """Get the current spot prices of all server types."""
        self._inventory_price_rounding(
            ServerPrice,
            self._get_methods().inventory_server_prices_spot,
            ServerPrice.allocation == Allocation.SPOT,
            prefix="spot",
        )

    @log_start_end
    def inventory_storages(self):
        """Get the vendor's all storage types."""
        self._inventory(Storage, self._get_methods().inventory_storages)

    @log_start_end
    def inventory_storage_prices(self):
        """Get the current prices of all storage types."""
        self._inventory_price_rounding(
            StoragePrice, self._get_methods().inventory_storage_prices
        )

    @log_start_end
    def inventory_traffic_prices(self):
        """Get the current prices of all traffic types."""
        self._inventory_price_rounding(
            TrafficPrice, self._get_methods().inventory_traffic_prices
        )

    @log_start_end
    def inventory_ipv4_prices(self):
        """Get the current prices of all IPv4 types."""
        self._inventory_price_rounding(
            Ipv4Price, self._get_methods().inventory_ipv4_prices
        )

    @log_start_end
    def inventory_databases(self):
        """Get the vendor's all managed database types."""
        self.set_table_rows_inactive(Database)
        databases = self._get_methods().inventory_databases(self)
        # show progress bar while downloading
        self.progress_tracker.start_task(
            name="Downloading sc-inspector-data", total=None
        )
        inspector_data_path()
        self.progress_tracker.hide_task()
        insert_items(Database, databases, self)
        benchmarks = []
        self.progress_tracker.start_task(
            name="Searching for database benchmark(s)", total=len(self.databases)
        )
        for database in self.databases:
            benchmarks += inspect_database_benchmarks(database)
            self.progress_tracker.advance_task()
        self.progress_tracker.hide_task()
        self.set_table_rows_inactive(
            BenchmarkScore,
            BenchmarkScore.vendor_id == self.vendor_id,
            BenchmarkScore.resource_type == ResourceType.DATABASE,
        )
        insert_items(BenchmarkScore, benchmarks, self, prefix="database")

    @log_start_end
    def inventory_database_prices(self):
        """Get the current prices of all managed database types."""
        self._inventory_price_rounding(
            DatabasePrice,
            self._get_methods().inventory_database_prices,
            DatabasePrice.allocation == Allocation.ONDEMAND,
            prefix="ondemand",
        )

    @log_start_end
    def inventory_database_storages(self):
        """Get the vendor's all managed database storage products."""
        self._inventory(
            DatabaseStorage, self._get_methods().inventory_database_storages
        )

    @log_start_end
    def inventory_database_storage_prices(self):
        """Get the current prices of all managed database storage products."""
        self._inventory_price_rounding(
            DatabaseStoragePrice,
            self._get_methods().inventory_database_storage_prices,
        )

session deletable property writable #

session

The Session to use for merging dependent objects into the database.

progress_tracker deletable property writable #

progress_tracker

The sc_crawler.logger.VendorProgressTracker to use for updating progress bars.

tasks property #

tasks

Reexport progress_tracker.tasks for easier access.

set_table_rows_inactive #

set_table_rows_inactive(model, *args)

Set this vendor's records to INACTIVE in a table.

Positional arguments can be used to pass further filters (besides the default model.vendor_id filter) referencing the model object with SQLModel syntax.

Records marked as ARCHIVED are kept as-is, just like the PLANNED_FOR_RETIREMENT and RETIRED servers and databases, so that these keep their status and retirement date when no longer returned by the vendor.

Examples:

>>> aws.set_table_rows_inactive(ServerPrice, ServerPrice.price < 10)
Source code in sc_crawler/tables.py
def set_table_rows_inactive(self, model: str, *args) -> None:
    """Set this vendor's records to [INACTIVE][sc_crawler.table_fields.Status] in a table.

    Positional arguments can be used to pass further filters
    (besides the default model.vendor_id filter) referencing the
    model object with SQLModel syntax.

    Records marked as [ARCHIVED][sc_crawler.table_fields.Status] are kept as-is,
    just like the `PLANNED_FOR_RETIREMENT` and `RETIRED` servers and databases,
    so that these keep their status and retirement date when no longer returned
    by the vendor.

    Examples:
        >>> aws.set_table_rows_inactive(ServerPrice, ServerPrice.price < 10)  # doctest: +SKIP
    """
    if self.session:
        query = (
            update(model)
            .where(model.vendor_id == self.vendor_id)
            .where(
                model.status.not_in(
                    [
                        Status.ARCHIVED,
                        Status.PLANNED_FOR_RETIREMENT,
                        Status.RETIRED,
                    ]
                )
            )
        )
        for arg in args:
            query = query.where(arg)
        self.session.exec(query.values(status=Status.INACTIVE))

set_table_rows_active #

set_table_rows_active(model, *args)

Set this vendor's records to ACTIVE in a table.

Positional arguments can be used to pass further filters (besides the default model.vendor_id filter) referencing the model object with SQLModel syntax.

Records marked as ARCHIVED are kept as-is.

Examples:

>>> aws.set_table_rows_active(ServerPrice, ServerPrice.price < 10)
Source code in sc_crawler/tables.py
def set_table_rows_active(self, model: str, *args) -> None:
    """Set this vendor's records to [ACTIVE][sc_crawler.table_fields.Status] in a table.

    Positional arguments can be used to pass further filters
    (besides the default model.vendor_id filter) referencing the
    model object with SQLModel syntax.

    Records marked as [ARCHIVED][sc_crawler.table_fields.Status] are kept as-is.

    Examples:
        >>> aws.set_table_rows_active(ServerPrice, ServerPrice.price < 10)  # doctest: +SKIP
    """
    if self.session:
        query = (
            update(model)
            .where(model.vendor_id == self.vendor_id)
            .where(model.status != Status.ARCHIVED)
        )
        for arg in args:
            query = query.where(arg)
        self.session.exec(query.values(status=Status.ACTIVE))

inventory_compliance_frameworks #

inventory_compliance_frameworks()

Get the vendor's all compliance frameworks.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_compliance_frameworks(self):
    """Get the vendor's all compliance frameworks."""
    self._inventory(
        VendorComplianceLink, self._get_methods().inventory_compliance_frameworks
    )

inventory_regions #

inventory_regions()

Get the vendor's all regions.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_regions(self):
    """Get the vendor's all regions."""
    self._inventory(Region, self._get_methods().inventory_regions)

inventory_zones #

inventory_zones()

Get all the zones in the vendor's regions.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_zones(self):
    """Get all the zones in the vendor's regions."""
    self._inventory(Zone, self._get_methods().inventory_zones)

inventory_servers #

inventory_servers()

Get the vendor's all server types.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_servers(self):
    """Get the vendor's all server types."""
    self.set_table_rows_inactive(Server)
    servers = self._get_methods().inventory_servers(self)
    # show progress bar while downloading
    self.progress_tracker.start_task(
        name="Downloading sc-inspector-data", total=None
    )
    inspector_data_path()
    self.progress_tracker.hide_task()
    # actual HW inspection
    for server in servers:
        server = inspect_update_server_dict(server)
    insert_items(Server, servers, self)
    benchmarks = []
    self.progress_tracker.start_task(
        name="Searching for server benchmark(s)", total=len(self.servers)
    )
    for server in self.servers:
        benchmarks += inspect_server_benchmarks(server)
        self.progress_tracker.advance_task()
    self.progress_tracker.hide_task()
    self.set_table_rows_inactive(
        BenchmarkScore,
        BenchmarkScore.vendor_id == self.vendor_id,
        BenchmarkScore.resource_type == ResourceType.SERVER,
    )
    insert_items(BenchmarkScore, benchmarks, self, prefix="server")
    self.progress_tracker.start_task(
        name="Downloading sc-navigator-descriptions", total=None
    )
    descriptions_data_path()
    self.progress_tracker.hide_task()
    descriptions = []
    self.progress_tracker.start_task(
        name="Loading server description(s)", total=len(self.servers)
    )
    for server in self.servers:
        description = ingest_server_description(server)
        if description is not None:
            descriptions.append(description)
        self.progress_tracker.advance_task()
    self.progress_tracker.hide_task()
    self.set_table_rows_inactive(
        ServerDescription, ServerDescription.vendor_id == self.vendor_id
    )
    insert_items(ServerDescription, descriptions, self)

inventory_server_prices #

inventory_server_prices()

Get the current standard/ondemand/reserved prices of all server types.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_server_prices(self):
    """Get the current standard/ondemand/reserved prices of all server types."""
    self._inventory_price_rounding(
        ServerPrice,
        self._get_methods().inventory_server_prices,
        ServerPrice.allocation == Allocation.ONDEMAND,
        prefix="ondemand",
    )

inventory_server_prices_spot #

inventory_server_prices_spot()

Get the current spot prices of all server types.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_server_prices_spot(self):
    """Get the current spot prices of all server types."""
    self._inventory_price_rounding(
        ServerPrice,
        self._get_methods().inventory_server_prices_spot,
        ServerPrice.allocation == Allocation.SPOT,
        prefix="spot",
    )

inventory_storages #

inventory_storages()

Get the vendor's all storage types.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_storages(self):
    """Get the vendor's all storage types."""
    self._inventory(Storage, self._get_methods().inventory_storages)

inventory_storage_prices #

inventory_storage_prices()

Get the current prices of all storage types.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_storage_prices(self):
    """Get the current prices of all storage types."""
    self._inventory_price_rounding(
        StoragePrice, self._get_methods().inventory_storage_prices
    )

inventory_traffic_prices #

inventory_traffic_prices()

Get the current prices of all traffic types.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_traffic_prices(self):
    """Get the current prices of all traffic types."""
    self._inventory_price_rounding(
        TrafficPrice, self._get_methods().inventory_traffic_prices
    )

inventory_ipv4_prices #

inventory_ipv4_prices()

Get the current prices of all IPv4 types.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_ipv4_prices(self):
    """Get the current prices of all IPv4 types."""
    self._inventory_price_rounding(
        Ipv4Price, self._get_methods().inventory_ipv4_prices
    )

inventory_databases #

inventory_databases()

Get the vendor's all managed database types.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_databases(self):
    """Get the vendor's all managed database types."""
    self.set_table_rows_inactive(Database)
    databases = self._get_methods().inventory_databases(self)
    # show progress bar while downloading
    self.progress_tracker.start_task(
        name="Downloading sc-inspector-data", total=None
    )
    inspector_data_path()
    self.progress_tracker.hide_task()
    insert_items(Database, databases, self)
    benchmarks = []
    self.progress_tracker.start_task(
        name="Searching for database benchmark(s)", total=len(self.databases)
    )
    for database in self.databases:
        benchmarks += inspect_database_benchmarks(database)
        self.progress_tracker.advance_task()
    self.progress_tracker.hide_task()
    self.set_table_rows_inactive(
        BenchmarkScore,
        BenchmarkScore.vendor_id == self.vendor_id,
        BenchmarkScore.resource_type == ResourceType.DATABASE,
    )
    insert_items(BenchmarkScore, benchmarks, self, prefix="database")

inventory_database_prices #

inventory_database_prices()

Get the current prices of all managed database types.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_database_prices(self):
    """Get the current prices of all managed database types."""
    self._inventory_price_rounding(
        DatabasePrice,
        self._get_methods().inventory_database_prices,
        DatabasePrice.allocation == Allocation.ONDEMAND,
        prefix="ondemand",
    )

inventory_database_storages #

inventory_database_storages()

Get the vendor's all managed database storage products.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_database_storages(self):
    """Get the vendor's all managed database storage products."""
    self._inventory(
        DatabaseStorage, self._get_methods().inventory_database_storages
    )

inventory_database_storage_prices #

inventory_database_storage_prices()

Get the current prices of all managed database storage products.

Source code in sc_crawler/tables.py
@log_start_end
def inventory_database_storage_prices(self):
    """Get the current prices of all managed database storage products."""
    self._inventory_price_rounding(
        DatabaseStoragePrice,
        self._get_methods().inventory_database_storage_prices,
    )

Bases: VendorComplianceLinkBase

List of known Compliance Frameworks paired with vendors.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

compliance_framework_id str

Reference to the Compliance Framework.

comment Optional[str]

Optional references, such as dates, URLs, and additional information/evidence.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class VendorComplianceLink(VendorComplianceLinkBase, table=True):
    """List of known Compliance Frameworks paired with vendors."""

    vendor: Vendor = Relationship(back_populates="compliance_framework_links")
    compliance_framework: ComplianceFramework = Relationship(
        back_populates="vendor_links"
    )

Region #

Bases: RegionBase

Regions of Vendors.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

region_id str

Unique identifier, as called at the Vendor.

name str

Human-friendly name.

api_reference str

How this resource is referenced in the vendor API calls. This is usually either the id or name of the resource, depending on the vendor and actual API endpoint.

display_name str

Human-friendly reference (usually the id or name) of the resource.

aliases List[str]

List of other commonly used names for the same Region.

country_id str

Reference to the Country, where the Region is located.

state Optional[str]

Optional state/administrative area of the Region's location within the Country.

city Optional[str]

Optional city name of the Region's location.

address_line Optional[str]

Optional address line of the Region's location.

zip_code Optional[str]

Optional ZIP code of the Region's location.

lon Optional[float]

Longitude coordinate of the Region's known or approximate location.

lat Optional[float]

Latitude coordinate of the Region's known or approximate location.

founding_year Optional[int]

4-digit year when the Region was founded.

green_energy Optional[bool]

If the Region is 100% powered by renewable energy.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class Region(RegionBase, table=True):
    """Regions of Vendors."""

    vendor: Vendor = Relationship(back_populates="regions")
    country: Country = Relationship(back_populates="regions")

    zones: List["Zone"] = Relationship(
        back_populates="region", sa_relationship_kwargs={"viewonly": True}
    )
    server_prices: List["ServerPrice"] = Relationship(
        back_populates="region", sa_relationship_kwargs={"viewonly": True}
    )
    traffic_prices: List["TrafficPrice"] = Relationship(
        back_populates="region", sa_relationship_kwargs={"viewonly": True}
    )
    ipv4_prices: List["Ipv4Price"] = Relationship(
        back_populates="region", sa_relationship_kwargs={"viewonly": True}
    )
    storage_prices: List["StoragePrice"] = Relationship(
        back_populates="region", sa_relationship_kwargs={"viewonly": True}
    )
    database_prices: List["DatabasePrice"] = Relationship(
        back_populates="region", sa_relationship_kwargs={"viewonly": True}
    )
    database_storage_prices: List["DatabaseStoragePrice"] = Relationship(
        back_populates="region", sa_relationship_kwargs={"viewonly": True}
    )

Zone #

Bases: ZoneBase

Availability zones of Regions.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

region_id str

Reference to the Region.

zone_id str

Unique identifier, as called at the Vendor.

name str

Human-friendly name.

api_reference str

How this resource is referenced in the vendor API calls. This is usually either the id or name of the resource, depending on the vendor and actual API endpoint.

display_name str

Human-friendly reference (usually the id or name) of the resource.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class Zone(ZoneBase, table=True):
    """Availability zones of Regions."""

    __table_args__ = (
        ForeignKeyConstraint(
            ["vendor_id", "region_id"],
            ["region.vendor_id", "region.region_id"],
        ),
    )

    region: Region = Relationship(
        back_populates="zones",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Region.region_id == foreign(Zone.region_id), "
                "Region.vendor_id == foreign(Zone.vendor_id))"
            ),
            "overlaps": "vendor",
        },
    )
    vendor: Vendor = Relationship(back_populates="zones")

    server_prices: List["ServerPrice"] = Relationship(
        back_populates="zone", sa_relationship_kwargs={"viewonly": True}
    )

Storage #

Bases: StorageBase

Flexible storage options that can be attached to a Server.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

storage_id str

Unique identifier, as called at the Vendor.

name str

Human-friendly name.

description Optional[str]

Short description.

storage_type StorageType

High-level category of the storage, e.g. HDD or SDD.

max_iops Optional[int]

Maximum Input/Output Operations Per Second.

max_throughput Optional[int]

Maximum Throughput (MB/s).

min_size Optional[int]

Minimum required size (GB).

max_size Optional[int]

Maximum possible size (GB).

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class Storage(StorageBase, table=True):
    """Flexible storage options that can be attached to a Server."""

    vendor: Vendor = Relationship(back_populates="storages")

    prices: List["StoragePrice"] = Relationship(
        back_populates="storage", sa_relationship_kwargs={"viewonly": True}
    )

Server #

Bases: ServerBase

Server types.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

server_id str

Unique identifier, as called at the Vendor.

name str

Human-friendly name.

api_reference str

How this resource is referenced in the vendor API calls. This is usually either the id or name of the resource, depending on the vendor and actual API endpoint.

api_reference_object Optional[dict]

How this resource is referenced in the vendor API calls, including the parameter name(s).

display_name str

Human-friendly reference (usually the id or name) of the resource.

description str

Short description.

family Optional[str]

Broad workload class of the server in the vendor's own naming, e.g. General Purpose, Compute Optimized or Memory Optimized.

series Optional[str]

Hardware line and generation of the server, e.g. m5 (AWS), n2 (GCP) or b3 (OVH).

vcpus int

Default number of virtual CPUs (vCPU) of the server.

hypervisor Optional[Hypervisor]

Hypervisor of the server, e.g. KVM, Xen, Nitro or Hyper-V, or Bare metal for servers without a hypervisor. Empty when not known.

cpu_allocation CpuAllocation

Allocation of CPU(s) to the server, e.g. shared, burstable or dedicated.

cpu_cores Optional[int]

Default number of CPU cores of the server. Equals to vCPUs when HyperThreading is disabled.

cpu_speed Optional[float]

Vendor-reported maximum CPU clock speed (GHz).

cpu_architecture CpuArchitecture

CPU architecture (arm64, arm64_mac, i386, or x86_64).

cpu_manufacturer Optional[str]

The manufacturer of the primary processor, e.g. Intel or AMD.

cpu_family Optional[str]

The product line/family of the primary processor, e.g. Xeon, Core i7, Ryzen 9.

cpu_model Optional[str]

The model number of the primary processor, e.g. 9750H.

cpu_l1d_cache Optional[int]

L1 data cache size (KiB).

cpu_l1d_cache_total Optional[int]

Total L1 data cache size (KiB) across all cores.

cpu_l1i_cache Optional[int]

L1 instruction cache size (KiB).

cpu_l1i_cache_total Optional[int]

Total L1 instruction cache size (KiB) across all cores.

cpu_l2_cache Optional[int]

L2 cache size (KiB).

cpu_l2_cache_total Optional[int]

Total L2 cache size (KiB) across all cores.

cpu_l3_cache Optional[int]

L3 cache size (KiB).

cpu_l3_cache_total Optional[int]

Total L3 cache size (KiB) across all cores.

cpu_flags List[str]

CPU features/flags.

cpus List[Cpu]

JSON array of known CPU details, e.g. the manufacturer, family, model; L1/L2/L3 cache size; microcode version; feature flags; bugs etc.

ecpus Optional[float]

The effective "real-world" core count, calculated by dividing the maximum multi-core SCore by the single-core SCore.

scalability Optional[float]

Measures how efficiently the server scales from a single core performance to using multiple cores. A score of 100% means perfect linear scaling with zero performance loss.

hw_virt Optional[bool]

If hardware virtualization (e.g. KVM) is supported.

memory_amount int

RAM amount (MiB) reported by the vendor.

memory_amount_actual Optional[int]

Actual RAM amount (MiB) measured on the instance via lstopo or other tool. This amount might not match the vendor-reported memory due to the BIOS or the hypervisor reserving a small percentage.

memory_generation Optional[DdrGeneration]

Generation of the DDR SDRAM, e.g. DDR4 or DDR5.

memory_speed Optional[int]

DDR SDRAM clock rate (Mhz).

memory_ecc Optional[bool]

If the DDR SDRAM uses error correction code to detect and correct n-bit data corruption.

accelerator_count float

Number of accelerator(s), e.g. GPUs or NPUs.

accelerator_memory_min Optional[int]

Memory (MiB) allocated to the lowest-end accelerator.

accelerator_memory_total Optional[int]

Overall memory (MiB) allocated to all the accelerator(s).

accelerator_type Optional[AcceleratorType]

The type of the primary accelerator, e.g. GPU or NPU.

accelerator_manufacturer Optional[str]

The manufacturer of the primary accelerator, e.g. Nvidia or AMD.

accelerator_family Optional[str]

The product family of the primary accelerator, e.g. Turing.

accelerator_model Optional[str]

The model number of the primary accelerator, e.g. Tesla T4.

accelerators List[Accelerator]

JSON array of accelerator details, including the manufacturer, name, and memory (MiB) of each accelerator.

storage_size int

Overall size (GB) of the disk(s).

storage_type Optional[StorageType]

Primary disk type, e.g. HDD, SSD, or NVMe SSD.

storages List[Disk]

JSON array of disks attached to the server, including the size (GB) and type of each disk.

storage_read_iops_max Optional[int]

The vendor-published maximum read IOPS of the bundled disk(s), summed over all disks, also of different types (e.g. temp disk and NVMe), so a theoretical total. Per-disk values are in storages.

storage_write_iops_max Optional[int]

The vendor-published maximum write IOPS of the bundled disk(s), summed over all disks, also of different types (e.g. temp disk and NVMe), so a theoretical total. Per-disk values are in storages.

storage_read_throughput_max Optional[int]

The vendor-published maximum read throughput (MB/s) of the bundled disk(s), summed over all disks, also of different types (e.g. temp disk and NVMe), so a theoretical total. Per-disk values are in storages.

storage_write_throughput_max Optional[int]

The vendor-published maximum write throughput (MB/s) of the bundled disk(s), summed over all disks, also of different types (e.g. temp disk and NVMe), so a theoretical total. Per-disk values are in storages.

compatible_storage_ids Optional[List[str]]

List of storage_ids that can be attached to the server as extra storage.

network_speed_baseline Optional[float]

The baseline network performance (Gbps) of the server, aggregated over all network cards.

network_speed_max Optional[float]

The maximum network performance (Gbps) of the server, aggregated over all network cards.

network_storage_speed_baseline Optional[float]

The baseline bandwidth performance of network-attached storage (Gbps).

network_storage_speed_max Optional[float]

The maximum bandwidth performance of network-attached storage (Gbps).

inbound_traffic float

Amount of complimentary inbound traffic (GB) per month.

outbound_traffic float

Amount of complimentary outbound traffic (GB) per month.

ipv4 int

Number of complimentary IPv4 address(es).

average_time_to_start Optional[float]

Average time to start the server (seconds).

retirement_date Optional[date]

Retirement date announced by the vendor for PLANNED_FOR_RETIREMENT and RETIRED records: the end of support (shutdown) if published, otherwise the end of sale. Empty when not announced or not known.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Methods:

Name Description
check_inspector_task_block_reasons

Check if the Server should run inspector task(s) and return block reasons.

Source code in sc_crawler/tables.py
class Server(ServerBase, table=True):
    """Server types."""

    def check_inspector_task_block_reasons(self, tasks: List[str]):
        """Check if the Server should run inspector task(s) and return block reasons."""
        return block_reasons(self, tasks)

    vendor: Vendor = Relationship(back_populates="servers")
    prices: List["ServerPrice"] = Relationship(
        back_populates="server", sa_relationship_kwargs={"viewonly": True}
    )
    benchmark_scores: List["BenchmarkScore"] = Relationship(
        back_populates="server",
        sa_relationship_kwargs={
            "viewonly": True,
            "primaryjoin": (
                "and_(Server.server_id == foreign(BenchmarkScore.resource_id), "
                "Server.vendor_id == foreign(BenchmarkScore.vendor_id), "
                "BenchmarkScore.resource_type == 'SERVER')"
            ),
        },
    )

check_inspector_task_block_reasons #

check_inspector_task_block_reasons(tasks)

Check if the Server should run inspector task(s) and return block reasons.

Source code in sc_crawler/tables.py
def check_inspector_task_block_reasons(self, tasks: List[str]):
    """Check if the Server should run inspector task(s) and return block reasons."""
    return block_reasons(self, tasks)

ServerPrice #

Bases: ServerPriceBase

Server type prices per Region and Allocation method.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

region_id str

Reference to the Region.

zone_id str

Reference to the Zone.

server_id str

Reference to the Server.

operating_system str

Operating System.

allocation Allocation

Allocation method, e.g. on-demand or spot.

unit PriceUnit

Billing unit of the pricing model.

price float

Actual price of a billing unit.

price_upfront float

Price to be paid when setting up the resource.

price_tiered List[PriceTier]

List of pricing tiers with min/max thresholds and actual prices.

currency str

Currency of the prices.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class ServerPrice(ServerPriceBase, table=True):
    """Server type prices per Region and Allocation method."""

    __table_args__ = (
        ForeignKeyConstraint(
            ["vendor_id", "region_id"],
            ["region.vendor_id", "region.region_id"],
        ),
        ForeignKeyConstraint(
            ["vendor_id", "region_id", "zone_id"],
            ["zone.vendor_id", "zone.region_id", "zone.zone_id"],
        ),
        ForeignKeyConstraint(
            ["vendor_id", "server_id"],
            ["server.vendor_id", "server.server_id"],
        ),
    )
    vendor: Vendor = Relationship(back_populates="server_prices")
    region: Region = Relationship(
        back_populates="server_prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Region.region_id == foreign(ServerPrice.region_id), "
                "Region.vendor_id == foreign(ServerPrice.vendor_id))"
            ),
            "overlaps": "vendor,zone,server",
        },
    )
    zone: Zone = Relationship(
        back_populates="server_prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Zone.zone_id == foreign(ServerPrice.zone_id), "
                "Zone.region_id == foreign(ServerPrice.region_id),"
                "Zone.vendor_id == foreign(ServerPrice.vendor_id))"
            ),
            "overlaps": "vendor,region,server",
        },
    )
    server: Server = Relationship(
        back_populates="prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Server.server_id == foreign(ServerPrice.server_id), "
                "Server.vendor_id == foreign(ServerPrice.vendor_id))"
            ),
            "overlaps": "vendor,region,zone",
        },
    )

ServerDescription #

Bases: ServerDescriptionBase

Variable length, plain English descriptions of Server hardware specs, performance, cost-efficiency, and workflow fit.

Attributes:

Name Type Description
page List[str]

Detailed server description with up to 500 words total across multiple paragraphs on hardware specs, benchmark-relative performance, qualitative cost efficiency, tradeoffs, and workload fit.

description str

Dense and technical server description using around 150 words in a single paragraph.

og_description str

200 character server description explicitly including vendor and server name.

meta_description str

150 character server description explicitly including vendor and server name.

tagline str

20-word tagline on server positioning and key differentiators without the vendor or server name.

bullet_points List[str]

4-6 concise bullet points highlighting key features and best-fit workloads.

categories List[Category]

One or more workload categories best fitting the server.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

vendor_id str

Reference to the Vendor.

server_id str

Unique identifier, as called at the Vendor.

Source code in sc_crawler/tables.py
class ServerDescription(ServerDescriptionBase, table=True):
    """Variable length, plain English descriptions of Server hardware specs, performance, cost-efficiency, and workflow fit."""

    __table_args__ = (
        ForeignKeyConstraint(
            ["vendor_id", "server_id"],
            ["server.vendor_id", "server.server_id"],
        ),
    )

StoragePrice #

Bases: StoragePriceBase

Flexible Storage prices in each Region.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

region_id str

Reference to the Region.

storage_id str

Reference to the Storage.

unit PriceUnit

Billing unit of the pricing model.

price float

Actual price of a billing unit.

price_upfront float

Price to be paid when setting up the resource.

price_tiered List[PriceTier]

List of pricing tiers with min/max thresholds and actual prices.

currency str

Currency of the prices.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class StoragePrice(StoragePriceBase, table=True):
    """Flexible Storage prices in each Region."""

    __table_args__ = (
        ForeignKeyConstraint(
            ["vendor_id", "region_id"],
            ["region.vendor_id", "region.region_id"],
        ),
        ForeignKeyConstraint(
            ["vendor_id", "storage_id"],
            ["storage.vendor_id", "storage.storage_id"],
        ),
    )
    vendor: Vendor = Relationship(back_populates="storage_prices")
    region: Region = Relationship(
        back_populates="storage_prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Region.region_id == foreign(StoragePrice.region_id),"
                "Region.vendor_id == foreign(StoragePrice.vendor_id))"
            ),
            "overlaps": "vendor,storage",
        },
    )
    storage: Storage = Relationship(
        back_populates="prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Storage.storage_id == foreign(StoragePrice.storage_id), "
                "Storage.vendor_id == foreign(StoragePrice.vendor_id))"
            ),
            "overlaps": "vendor,region",
        },
    )

Database #

Bases: DatabaseBase

Managed database SKUs.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

database_id str

Unique identifier, as called at the Vendor.

name str

Human-friendly name.

api_reference str

How this resource is referenced in the vendor API calls. This is usually either the id or name of the resource, depending on the vendor and actual API endpoint.

api_reference_object Optional[dict]

How this resource is referenced in the vendor API calls, including the parameter name(s).

display_name str

Human-friendly reference (usually the id or name) of the resource.

description Optional[str]

Short description.

family Optional[str]

Broad workload class of the database in the vendor's own naming, e.g. General Purpose or Memory Optimized.

series Optional[str]

Hardware line and generation of the database, matching the series of the server it runs on, where known.

server_id Optional[str]

Reference to the underlying cloud server's identifier.

vcpus Optional[int]

Number of virtual CPU cores allocated to the database server instance.

memory_amount Optional[int]

Amount of RAM (MiB) provisioned for the instance.

engine Optional[DatabaseEngine]

Managed database engine running on the instance.

wire_protocol Optional[DatabaseWireProtocol]

Network protocol used for client connections.

engine_versions List[str]

Major database engine versions supported.

auto_upgrade_versions Optional[bool]

Auto-upgrade between minor database engine versions.

ha List[DatabaseHaLevel]

Ordered HA levels supported, highest tier first.

ha_strategy List[DatabaseHaStrategy]

Ordered HA strategies supported, highest tier first.

max_read_replicas Optional[int]

Maximum number of read-only replica nodes supported to scale read workloads.

custom_config Optional[bool]

Whether database engine parameters/flags can be customized.

custom_extensions Optional[bool]

Support for custom database engine extensions/plugins.

storage_size Optional[int]

Bundled storage capacity included in the database (GB).

storage_extra_min Optional[int]

Minimum custom storage size (in GB) that can be attached to the instance.

storage_extra_max Optional[int]

Maximum storage limit (in GB) supported by the instance or storage tier.

storage_extra_autosize Optional[bool]

Whether storage capacity can automatically expand as disk usage grows.

compatible_storage_ids Optional[List[str]]

List of database_storage_ids that can be attached to the database as extra storage.

disk_encryption Optional[bool]

Indicates whether underlying storage drives are encrypted at rest.

scheduled_backups Optional[bool]

Support for automated snapshot schedules and backup retention management.

continuous_backups Optional[int]

Maximum point-in-time recovery (PITR) log retention window expressed in days (0 if unsupported).

connection_pool Optional[bool]

Managed connection proxy support.

system_monitoring Optional[bool]

Availability of host-level CPU, RAM, and disk metrics dashboards.

database_monitoring Optional[bool]

Database engine performance insights (slow queries, locks, execution plans).

autotuning_advice Optional[bool]

Analyzes workload and generates actionable performance tuning advice.

autotuning_apply Optional[bool]

System automatically executes performance fixes (e.g., index creation, parameter tuning) without operator intervention.

sla Optional[float]

Service level agreement as a percentage, e.g. 99.95.

security_features List[DatabaseSecurityFeature]

Security capabilities supported by DBaaS providers.

retirement_date Optional[date]

Retirement date announced by the vendor for PLANNED_FOR_RETIREMENT and RETIRED records: the end of support (shutdown) if published, otherwise the end of sale. Empty when not announced or not known.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Methods:

Name Description
check_inspector_task_block_reasons

Check if the Database should run inspector task(s) and return block reasons.

Source code in sc_crawler/tables.py
class Database(DatabaseBase, table=True):
    """Managed database SKUs."""

    def check_inspector_task_block_reasons(self, tasks: List[str]):
        """Check if the Database should run inspector task(s) and return block reasons."""
        return block_reasons(self, tasks)

    vendor: Vendor = Relationship(back_populates="databases")
    prices: List["DatabasePrice"] = Relationship(
        back_populates="database", sa_relationship_kwargs={"viewonly": True}
    )
    benchmark_scores: List["BenchmarkScore"] = Relationship(
        back_populates="database",
        sa_relationship_kwargs={
            "viewonly": True,
            "primaryjoin": (
                "and_(Database.database_id == foreign(BenchmarkScore.resource_id), "
                "Database.vendor_id == foreign(BenchmarkScore.vendor_id), "
                "BenchmarkScore.resource_type == 'DATABASE')"
            ),
        },
    )

check_inspector_task_block_reasons #

check_inspector_task_block_reasons(tasks)

Check if the Database should run inspector task(s) and return block reasons.

Source code in sc_crawler/tables.py
def check_inspector_task_block_reasons(self, tasks: List[str]):
    """Check if the Database should run inspector task(s) and return block reasons."""
    return block_reasons(self, tasks)

DatabasePrice #

Bases: DatabasePriceBase

Managed database SKU prices per Region.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

region_id str

Reference to the Region.

database_id str

Reference to the Database.

allocation Allocation

Allocation method, e.g. on-demand or spot.

ha DatabaseHaLevel

HA level this price applies to.

ha_strategy DatabaseHaStrategy

HA strategy this price applies to.

unit PriceUnit

Billing unit of the pricing model.

price float

Actual price of a billing unit.

price_upfront float

Price to be paid when setting up the resource.

price_tiered List[PriceTier]

List of pricing tiers with min/max thresholds and actual prices.

currency str

Currency of the prices.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class DatabasePrice(DatabasePriceBase, table=True):
    """Managed database SKU prices per Region."""

    __table_args__ = (
        ForeignKeyConstraint(
            ["vendor_id", "region_id"],
            ["region.vendor_id", "region.region_id"],
        ),
        ForeignKeyConstraint(
            ["vendor_id", "database_id"],
            ["database.vendor_id", "database.database_id"],
        ),
    )
    vendor: Vendor = Relationship(back_populates="database_prices")
    region: Region = Relationship(
        back_populates="database_prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Region.region_id == foreign(DatabasePrice.region_id), "
                "Region.vendor_id == foreign(DatabasePrice.vendor_id))"
            ),
            "overlaps": "vendor,database",
        },
    )
    database: Database = Relationship(
        back_populates="prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Database.database_id == foreign(DatabasePrice.database_id), "
                "Database.vendor_id == foreign(DatabasePrice.vendor_id))"
            ),
            "overlaps": "vendor,region",
        },
    )

DatabaseStorage #

Bases: DatabaseStorageBase

Managed database storage products.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

database_storage_id str

Unique identifier, as called at the Vendor.

name str

Human-friendly name.

description Optional[str]

Short description.

scope DatabaseStorageScope

Scope of the storage product, e.g. data or backup.

redundancy Optional[str]

Redundancy model, e.g. LRS or GRS.

min_size Optional[int]

Minimum required size (GB).

max_size Optional[int]

Maximum possible size (GB).

max_iops Optional[int]

Maximum Input/Output Operations Per Second.

max_throughput Optional[int]

Maximum Throughput (MB/s).

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class DatabaseStorage(DatabaseStorageBase, table=True):
    """Managed database storage products."""

    vendor: Vendor = Relationship(back_populates="database_storages")
    prices: List["DatabaseStoragePrice"] = Relationship(
        back_populates="database_storage",
        sa_relationship_kwargs={"viewonly": True},
    )

DatabaseStoragePrice #

Bases: DatabaseStoragePriceBase

Managed database storage prices in each Region.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

region_id str

Reference to the Region.

database_storage_id str

Reference to the DatabaseStorage.

unit PriceUnit

Billing unit of the pricing model.

price float

Actual price of a billing unit.

price_upfront float

Price to be paid when setting up the resource.

price_tiered List[PriceTier]

List of pricing tiers with min/max thresholds and actual prices.

currency str

Currency of the prices.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class DatabaseStoragePrice(DatabaseStoragePriceBase, table=True):
    """Managed database storage prices in each Region."""

    __table_args__ = (
        ForeignKeyConstraint(
            ["vendor_id", "region_id"],
            ["region.vendor_id", "region.region_id"],
        ),
        ForeignKeyConstraint(
            ["vendor_id", "database_storage_id"],
            ["database_storage.vendor_id", "database_storage.database_storage_id"],
        ),
    )
    vendor: Vendor = Relationship(back_populates="database_storage_prices")
    region: Region = Relationship(
        back_populates="database_storage_prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Region.region_id == foreign(DatabaseStoragePrice.region_id),"
                "Region.vendor_id == foreign(DatabaseStoragePrice.vendor_id))"
            ),
            "overlaps": "vendor,database_storage",
        },
    )
    database_storage: DatabaseStorage = Relationship(
        back_populates="prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(DatabaseStorage.database_storage_id == "
                "foreign(DatabaseStoragePrice.database_storage_id), "
                "DatabaseStorage.vendor_id == "
                "foreign(DatabaseStoragePrice.vendor_id))"
            ),
            "overlaps": "vendor,region",
        },
    )

TrafficPrice #

Bases: TrafficPriceBase

Extra Traffic prices in each Region.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

region_id str

Reference to the Region.

direction TrafficDirection

Direction of the traffic: inbound or outbound.

unit PriceUnit

Billing unit of the pricing model.

price float

Actual price of a billing unit.

price_upfront float

Price to be paid when setting up the resource.

price_tiered List[PriceTier]

List of pricing tiers with min/max thresholds and actual prices.

currency str

Currency of the prices.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class TrafficPrice(TrafficPriceBase, table=True):
    """Extra Traffic prices in each Region."""

    __table_args__ = (
        ForeignKeyConstraint(
            ["vendor_id", "region_id"],
            ["region.vendor_id", "region.region_id"],
        ),
    )
    vendor: Vendor = Relationship(back_populates="traffic_prices")
    region: Region = Relationship(
        back_populates="traffic_prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Region.region_id == foreign(TrafficPrice.region_id),"
                "Region.vendor_id == foreign(TrafficPrice.vendor_id))"
            ),
            "overlaps": "vendor",
        },
    )

Ipv4Price #

Bases: Ipv4PriceBase

Price of an IPv4 address in each Region.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

region_id str

Reference to the Region.

unit PriceUnit

Billing unit of the pricing model.

price float

Actual price of a billing unit.

price_upfront float

Price to be paid when setting up the resource.

price_tiered List[PriceTier]

List of pricing tiers with min/max thresholds and actual prices.

currency str

Currency of the prices.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class Ipv4Price(Ipv4PriceBase, table=True):
    """Price of an IPv4 address in each Region."""

    __table_args__ = (
        ForeignKeyConstraint(
            ["vendor_id", "region_id"],
            ["region.vendor_id", "region.region_id"],
        ),
    )
    vendor: Vendor = Relationship(back_populates="ipv4_prices")
    region: Region = Relationship(
        back_populates="ipv4_prices",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Region.region_id == foreign(Ipv4Price.region_id),"
                "Region.vendor_id == foreign(Ipv4Price.vendor_id))"
            ),
            "overlaps": "vendor",
        },
    )

Benchmark #

Bases: BenchmarkBase

Benchmark scenario definitions.

Attributes:

Name Type Description
benchmark_id str

Unique identifier of a specific Benchmark.

category Optional[str]

Category of the resource.

subcategory Optional[str]

Subcategory of the benchmark within its category, e.g. the scope of an nvbandwidth test.

source Union[MeasuredSource, ExtrapolatedSource, CompoundSource]

How the benchmark score is produced. A discriminated object keyed by 'kind': 'measured' (directly observed), 'extrapolated' (derived from this server's own measurements; carries 'derived_from' + 'note'), or 'compound' (aggregated across component benchmarks; carries 'aggregation', 'normalization', and the 'components' recipe).

name str

Human-friendly name.

description Optional[str]

Short description.

note Optional[str]

Optional caveat/comment on how to interpret the metric, surfaced as a warning/info badge (e.g. limited scaling on high vCPU counts, or independence from vCPU count). Null when there is nothing to flag.

framework str

The name of the benchmark framework/software/tool used.

config_fields dict

A dictionary of descriptions on the framework-specific config options, e.g. {"bandwidth": "Memory amount to use for compression in MB."}.

environment_fields dict

A dictionary of descriptions on the environment details recorded with the benchmark scores, e.g. {"kernel_version": "Linux kernel version of the server."}.

measurement Optional[str]

The name of measurement recorded in the benchmark.

unit Optional[str]

Optional unit of measurement for the benchmark score.

higher_is_better bool

If higher benchmark score means better performance, or vica versa.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class Benchmark(BenchmarkBase, table=True):
    """Benchmark scenario definitions."""

    benchmark_scores: List["BenchmarkScore"] = Relationship(
        back_populates="benchmark", sa_relationship_kwargs={"viewonly": True}
    )

BenchmarkScore #

Bases: BenchmarkScoreBase

Results of running Benchmark scenarios on Servers or managed Databases.

Attributes:

Name Type Description
vendor_id str

Reference to the Vendor.

benchmark_id str

Reference to the Benchmark.

resource_type ResourceType

Kind of resource the score refers to.

resource_id str

Reference to the resource (see resource_type).

config HashableDict | dict

Dictionary of config parameters of the specific benchmark, e.g. {"bandwidth": 4096}

framework_version Optional[str]

The version of the benchmark tool used.

environment Optional[dict]

Extensible environment details (e.g. kernel_version, database_engine_version).

score float

The resulting score of the benchmark.

score_breakdown Optional[WorkloadScoreBreakdown]

Structured derivation of composite scores (e.g. workload profiles): per-component raw values, references, normalized values, weights, and coverage. Null for simple benchmark scores.

note Optional[str]

Optional note, comment or context on the benchmark score.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Source code in sc_crawler/tables.py
class BenchmarkScore(BenchmarkScoreBase, table=True):
    """Results of running Benchmark scenarios on Servers or managed Databases."""

    vendor: Vendor = Relationship(back_populates="benchmark_scores")
    server: Optional[Server] = Relationship(
        back_populates="benchmark_scores",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Server.server_id == foreign(BenchmarkScore.resource_id), "
                "Server.vendor_id == foreign(BenchmarkScore.vendor_id), "
                "BenchmarkScore.resource_type == 'SERVER')"
            ),
            "overlaps": "vendor,database",
            "viewonly": True,
        },
    )
    database: Optional[Database] = Relationship(
        back_populates="benchmark_scores",
        sa_relationship_kwargs={
            "primaryjoin": (
                "and_(Database.database_id == foreign(BenchmarkScore.resource_id), "
                "Database.vendor_id == foreign(BenchmarkScore.vendor_id), "
                "BenchmarkScore.resource_type == 'DATABASE')"
            ),
            "overlaps": "vendor,server",
            "viewonly": True,
        },
    )
    benchmark: Benchmark = Relationship(back_populates="benchmark_scores")

ArchiveRule #

Bases: ArchiveRuleBase

Rules archiving records that were replaced by another record or deliberately dropped.

The rules are defined in sc_crawler.archive_rules, and are applied by the pull and sync commands (see apply), which set the matched records and their child records to ARCHIVED.

Examples:

>>> from sc_crawler.tables import ArchiveRule
>>> ArchiveRule(table_name="benchmark", match={"benchmark_id": "foo"}, reason="Dropped.")
ArchiveRule(table_name='benchmark', match={'benchmark_id': 'foo'}, reason='Dropped.', successor={}...

Attributes:

Name Type Description
table_name str

Name of the table of the archived record(s), e.g. region.

match HashableDict | dict

Primary key of the record to archive, or a subset of its columns to archive all records with those values, e.g. {"region_id": "2", "vendor_id": "hcloud"}.

successor HashableDict | dict

New values of the match columns identifying the successor of each archived record. Empty when there is no successor, or none that can be given as fixed values (see reason).

reason Optional[str]

Why the record(s) got archived.

status Status

Status of the resource (active or inactive).

observed_at datetime

Timestamp of the last observation.

Methods:

Name Description
apply

Store the rules in the database, and archive the records they match.

find_unmatched

Describe the rules referring to records that are in none of the databases.

check

Check the definition of the rules, without a database.

Source code in sc_crawler/tables.py
class ArchiveRule(ArchiveRuleBase, table=True):
    """Rules archiving records that were replaced by another record or deliberately dropped.

    The rules are defined in [sc_crawler.archive_rules][], and are applied by
    the `pull` and `sync` commands (see [apply][sc_crawler.tables.ArchiveRule.apply]), which set the matched
    records and their child records to [ARCHIVED][sc_crawler.table_fields.Status].

    Examples:
        >>> from sc_crawler.tables import ArchiveRule
        >>> ArchiveRule(table_name="benchmark", match={"benchmark_id": "foo"}, reason="Dropped.")
        ArchiveRule(table_name='benchmark', match={'benchmark_id': 'foo'}, reason='Dropped.', successor={}...
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # SQLModel does not run validators on table models
        self.match = HashableDict.sorted(self.match)
        self.successor = HashableDict.sorted(self.successor)

    @classmethod
    def apply(
        cls, session: Session, rules: Optional[List["ArchiveRule"]] = None
    ) -> Dict[str, int]:
        """Store the rules in the database, and archive the records they match.

        All rules are written to the `archive_rule` table (also the ones not
        matching any record), then the matched records and their child records
        are set to [ARCHIVED][sc_crawler.table_fields.Status].

        Args:
            session: Database connection. Changes are not committed.
            rules: Rules to apply. Defaults to all current rules.

        Returns:
            Number of newly archived records per table name.
        """
        if rules is None:
            from .archive_rules import archive_rules as rules
        items = [rule.model_dump(exclude={"observed_at"}) for rule in rules]
        insert_items(cls, items, session=session)
        archived = {}
        for model in tables:
            condition = model.archive_condition(rules)
            if condition is None:
                continue
            result = session.exec(
                update(model)
                .where(condition)
                .where(model.status != Status.ARCHIVED)
                .values(status=Status.ARCHIVED)
            )
            if result.rowcount:
                archived[model.get_table_name()] = result.rowcount
        return archived

    @classmethod
    def find_unmatched(
        cls,
        sessions: List[Session],
        table_names: Optional[List[str]] = None,
        rules: Optional[List["ArchiveRule"]] = None,
    ) -> List[str]:
        """Describe the rules referring to records that are in none of the databases.

        Checks both the `match` and the (non-empty) `successor` of the rules,
        e.g. to find typos in the ids, or successors not provided by the vendor.

        Args:
            sessions: Connections to the databases to look up the records in.
            table_names: Check only the rules of these tables. Defaults to all tables.
            rules: Rules to check. Defaults to all current rules.

        Returns:
            A message for each `match` or `successor` without any record.
        """
        if rules is None:
            from .archive_rules import archive_rules as rules
        messages = []
        for rule in rules:
            if table_names is not None and rule.table_name not in table_names:
                continue
            model = table_name_to_model(rule.table_name)
            for field in ("match", "successor"):
                keys = getattr(rule, field)
                if not keys:
                    continue
                query = (
                    select(literal(1))
                    .select_from(model)
                    .where(model.get_filters_condition(keys))
                    .limit(1)
                )
                if not any(session.exec(query).first() for session in sessions):
                    messages.append(
                        f"Archive rule {rule.table_name} {dict(rule.match)} -> "
                        f"{dict(rule.successor)}: no record found for its {field}."
                    )
        return messages

    @classmethod
    def check(cls, rules: Optional[List["ArchiveRule"]] = None) -> List[str]:
        """Check the definition of the rules, without a database.

        Args:
            rules: Rules to check. Defaults to all current rules.

        Returns:
            Description of the problems found: unknown tables, `match` keys that
                are not primary key columns of the table, `successor` with other
                keys than `match`, enum columns not given by the value of a
                member, missing `reason` of rules without a successor,
                and rules leading back to a record they archived (cycles).
        """
        if rules is None:
            from .archive_rules import archive_rules as rules
        problems = []
        valid = []
        for rule in rules:
            label = f"{rule.table_name} {dict(rule.match)} -> {dict(rule.successor)}"
            if rule.table_name.endswith("_scd"):
                problems.append(f"{label}: rules cannot refer to SCD tables")
                continue
            try:
                model = table_name_to_model(rule.table_name)
            except ValueError:
                problems.append(f"{label}: unknown table")
                continue
            primary_keys = model.get_columns()["primary_keys"]
            if not rule.match:
                problems.append(f"{label}: empty match")
                continue
            unknown = [key for key in rule.match if key not in primary_keys]
            if unknown:
                problems.append(f"{label}: match keys {unknown} are not primary keys")
                continue
            if rule.successor and set(rule.successor) != set(rule.match):
                problems.append(f"{label}: successor and match have different keys")
                continue
            # enum members are stored by name, but a rule given by the name
            # would match only in SQL and not when comparing in Python
            invalid = []
            for keys in (rule.match, rule.successor):
                for key, value in keys.items():
                    column_type = model.__table__.columns[key].type
                    if (
                        isinstance(column_type, SaEnum)
                        and column_type.enum_class is not None
                        and value not in [m.value for m in column_type.enum_class]
                    ):
                        invalid.append(f"{key}={value!r}")
            if invalid:
                problems.append(
                    f"{label}: {', '.join(invalid)} is not the value of an enum member"
                )
                continue
            if rule.successor == rule.match:
                problems.append(f"{label}: the successor is the archived record itself")
                continue
            if not rule.successor and not rule.reason:
                problems.append(
                    f"{label}: no reason given for a rule without successor"
                )
            valid.append(rule)

        def leads_back(start: ArchiveRule, known: dict, path: tuple) -> bool:
            """Follow the rules from the successor of `start`, with `known` key columns."""
            if all(known.get(k, start) == v for k, v in start.match.items()):
                return True
            return any(
                leads_back(
                    start, {**known, **rule.match, **rule.successor}, path + (i,)
                )
                for i, rule in enumerate(valid)
                if i not in path
                and rule.successor
                and rule.table_name == start.table_name
                # `known` holds the key columns set by the rules followed so far,
                # the other columns can have any value
                and all(known.get(k, v) == v for k, v in rule.match.items())
            )

        for i, rule in enumerate(valid):
            if rule.successor and leads_back(rule, dict(rule.successor), (i,)):
                problems.append(
                    f"{rule.table_name} {dict(rule.match)} -> {dict(rule.successor)}: "
                    "following the rules leads back to the archived record"
                )
        return problems

apply classmethod #

apply(session, rules=None)

Store the rules in the database, and archive the records they match.

All rules are written to the archive_rule table (also the ones not matching any record), then the matched records and their child records are set to ARCHIVED.

Parameters:

Name Type Description Default
session Session

Database connection. Changes are not committed.

required
rules Optional[List[ArchiveRule]]

Rules to apply. Defaults to all current rules.

None

Returns:

Type Description
Dict[str, int]

Number of newly archived records per table name.

Source code in sc_crawler/tables.py
@classmethod
def apply(
    cls, session: Session, rules: Optional[List["ArchiveRule"]] = None
) -> Dict[str, int]:
    """Store the rules in the database, and archive the records they match.

    All rules are written to the `archive_rule` table (also the ones not
    matching any record), then the matched records and their child records
    are set to [ARCHIVED][sc_crawler.table_fields.Status].

    Args:
        session: Database connection. Changes are not committed.
        rules: Rules to apply. Defaults to all current rules.

    Returns:
        Number of newly archived records per table name.
    """
    if rules is None:
        from .archive_rules import archive_rules as rules
    items = [rule.model_dump(exclude={"observed_at"}) for rule in rules]
    insert_items(cls, items, session=session)
    archived = {}
    for model in tables:
        condition = model.archive_condition(rules)
        if condition is None:
            continue
        result = session.exec(
            update(model)
            .where(condition)
            .where(model.status != Status.ARCHIVED)
            .values(status=Status.ARCHIVED)
        )
        if result.rowcount:
            archived[model.get_table_name()] = result.rowcount
    return archived

find_unmatched classmethod #

find_unmatched(sessions, table_names=None, rules=None)

Describe the rules referring to records that are in none of the databases.

Checks both the match and the (non-empty) successor of the rules, e.g. to find typos in the ids, or successors not provided by the vendor.

Parameters:

Name Type Description Default
sessions List[Session]

Connections to the databases to look up the records in.

required
table_names Optional[List[str]]

Check only the rules of these tables. Defaults to all tables.

None
rules Optional[List[ArchiveRule]]

Rules to check. Defaults to all current rules.

None

Returns:

Type Description
List[str]

A message for each match or successor without any record.

Source code in sc_crawler/tables.py
@classmethod
def find_unmatched(
    cls,
    sessions: List[Session],
    table_names: Optional[List[str]] = None,
    rules: Optional[List["ArchiveRule"]] = None,
) -> List[str]:
    """Describe the rules referring to records that are in none of the databases.

    Checks both the `match` and the (non-empty) `successor` of the rules,
    e.g. to find typos in the ids, or successors not provided by the vendor.

    Args:
        sessions: Connections to the databases to look up the records in.
        table_names: Check only the rules of these tables. Defaults to all tables.
        rules: Rules to check. Defaults to all current rules.

    Returns:
        A message for each `match` or `successor` without any record.
    """
    if rules is None:
        from .archive_rules import archive_rules as rules
    messages = []
    for rule in rules:
        if table_names is not None and rule.table_name not in table_names:
            continue
        model = table_name_to_model(rule.table_name)
        for field in ("match", "successor"):
            keys = getattr(rule, field)
            if not keys:
                continue
            query = (
                select(literal(1))
                .select_from(model)
                .where(model.get_filters_condition(keys))
                .limit(1)
            )
            if not any(session.exec(query).first() for session in sessions):
                messages.append(
                    f"Archive rule {rule.table_name} {dict(rule.match)} -> "
                    f"{dict(rule.successor)}: no record found for its {field}."
                )
    return messages

check classmethod #

check(rules=None)

Check the definition of the rules, without a database.

Parameters:

Name Type Description Default
rules Optional[List[ArchiveRule]]

Rules to check. Defaults to all current rules.

None

Returns:

Type Description
List[str]

Description of the problems found: unknown tables, match keys that are not primary key columns of the table, successor with other keys than match, enum columns not given by the value of a member, missing reason of rules without a successor, and rules leading back to a record they archived (cycles).

Source code in sc_crawler/tables.py
@classmethod
def check(cls, rules: Optional[List["ArchiveRule"]] = None) -> List[str]:
    """Check the definition of the rules, without a database.

    Args:
        rules: Rules to check. Defaults to all current rules.

    Returns:
        Description of the problems found: unknown tables, `match` keys that
            are not primary key columns of the table, `successor` with other
            keys than `match`, enum columns not given by the value of a
            member, missing `reason` of rules without a successor,
            and rules leading back to a record they archived (cycles).
    """
    if rules is None:
        from .archive_rules import archive_rules as rules
    problems = []
    valid = []
    for rule in rules:
        label = f"{rule.table_name} {dict(rule.match)} -> {dict(rule.successor)}"
        if rule.table_name.endswith("_scd"):
            problems.append(f"{label}: rules cannot refer to SCD tables")
            continue
        try:
            model = table_name_to_model(rule.table_name)
        except ValueError:
            problems.append(f"{label}: unknown table")
            continue
        primary_keys = model.get_columns()["primary_keys"]
        if not rule.match:
            problems.append(f"{label}: empty match")
            continue
        unknown = [key for key in rule.match if key not in primary_keys]
        if unknown:
            problems.append(f"{label}: match keys {unknown} are not primary keys")
            continue
        if rule.successor and set(rule.successor) != set(rule.match):
            problems.append(f"{label}: successor and match have different keys")
            continue
        # enum members are stored by name, but a rule given by the name
        # would match only in SQL and not when comparing in Python
        invalid = []
        for keys in (rule.match, rule.successor):
            for key, value in keys.items():
                column_type = model.__table__.columns[key].type
                if (
                    isinstance(column_type, SaEnum)
                    and column_type.enum_class is not None
                    and value not in [m.value for m in column_type.enum_class]
                ):
                    invalid.append(f"{key}={value!r}")
        if invalid:
            problems.append(
                f"{label}: {', '.join(invalid)} is not the value of an enum member"
            )
            continue
        if rule.successor == rule.match:
            problems.append(f"{label}: the successor is the archived record itself")
            continue
        if not rule.successor and not rule.reason:
            problems.append(
                f"{label}: no reason given for a rule without successor"
            )
        valid.append(rule)

    def leads_back(start: ArchiveRule, known: dict, path: tuple) -> bool:
        """Follow the rules from the successor of `start`, with `known` key columns."""
        if all(known.get(k, start) == v for k, v in start.match.items()):
            return True
        return any(
            leads_back(
                start, {**known, **rule.match, **rule.successor}, path + (i,)
            )
            for i, rule in enumerate(valid)
            if i not in path
            and rule.successor
            and rule.table_name == start.table_name
            # `known` holds the key columns set by the rules followed so far,
            # the other columns can have any value
            and all(known.get(k, v) == v for k, v in rule.match.items())
        )

    for i, rule in enumerate(valid):
        if rule.successor and leads_back(rule, dict(rule.successor), (i,)):
            problems.append(
                f"{rule.table_name} {dict(rule.match)} -> {dict(rule.successor)}: "
                "following the rules leads back to the archived record"
            )
    return problems

is_table #

is_table(table)

Checks if an object is a SQLModel table definition.

Source code in sc_crawler/tables.py
def is_table(table):
    """Checks if an object is a SQLModel table definition."""
    try:
        return table.model_config["table"] is True
    except Exception:
        return False

tables module-attribute #

tables = [o for o in globals().values() if is_table(o)]

List of all SQLModel (table) models.

Metadata #

Bases: SQLModel

Key/value metadata table for database release information.

Source code in sc_crawler/tables.py
class Metadata(SQLModel, table=True):
    """Key/value metadata table for database release information."""

    __tablename__ = "_metadata"
    key: str = Field(primary_key=True)
    value: str