Skip to main content

Schema Overview

Ampra uses a dual-database architecture: PostgreSQL for relational data with referential integrity, and MongoDB for high-volume time-series telemetry and prediction data.


PostgreSQL — Relational Database

Database: ampradb · ORM: Entity Framework Core · Provider: Npgsql

Entity Relationship Diagram

Legend: PK = Primary Key · FK = Foreign Key · UK = Unique Key · IX = Index


Table Reference

Users (ApplicationUser)

Extends ASP.NET Identity's IdentityUser with custom fields for email verification and profile data.

ColumnTypeNullableDefaultDescription
IdtextNoGUIDPrimary key (Identity-generated)
UserNametextYesDisplay name
EmailtextYesUnique email address
NormalizedEmailtextYesUpper-case email for lookups
PasswordHashtextYesPBKDF2-hashed password
FirstNametextYesUser's first name
LastNametextYesUser's last name
CreatedAttimestamp with time zoneNoUTC NOWRegistration timestamp
IsEmailVerifiedbooleanNofalseEmail verification status
EmailVerificationCodetextYes6-digit verification code
EmailVerificationCodeExpirytimestamp with time zoneYesCode expiration time
LastCodeSentAttimestamp with time zoneYesRate limiting for code resend
FailedVerificationAttemptsintegerNo0Counter for lockout logic
VerificationLockoutUntiltimestamp with time zoneYesLockout expiry after failed attempts

Indexes:

  • EmailIndex on NormalizedEmail
  • UserNameIndex (unique) on NormalizedUserName

PowerGroups

Logical grouping of sun sources for organizational hierarchy (e.g., by site, region, or customer).

ColumnTypeNullableConstraintDescription
IduuidNoPKAuto-generated GUID
Namevarchar(100)NoRequiredDisplay name for the group
Descriptionvarchar(500)YesOptional description
LogoUrlvarchar(500)YesURL to group logo in MinIO
UserIdtextNoFK → Users.IdOwner of this power group
CreatedAttimestamp with time zoneNoDefault UTC NOWCreation timestamp
UpdatedAttimestamp with time zoneNoDefault UTC NOWLast modification timestamp

Relationships:

  • One-to-Many with SunSources (ON DELETE SET NULL — sources become ungrouped)
  • Many-to-One with Users (ON DELETE CASCADE — user deletion removes all groups)

Indexes: UserId


SunSources

The core entity representing a monitored solar energy installation.

ColumnTypeNullableConstraintDescription
IduuidNoPKAuto-generated GUID
Namevarchar(100)NoRequiredDisplay name
Descriptionvarchar(500)YesOptional description
IconUrltextYesCustom icon URL
UserIdtextNoFK → Users.IdOwner
PowerGroupIduuidYesFK → PowerGroups.IdOptional group assignment
ConnectionTypeintegerNoEnum0 = MQTT, 1 = Webhook
Latitudedouble precisionYes[-90, 90]GPS latitude
Longitudedouble precisionYes[-180, 180]GPS longitude
MqttTopictextYesAssigned MQTT topic path
MqttApiKeytextYes64-char hex API key for MQTT auth
WebhookUrltextYesGenerated webhook URL
WebhookSecrettextYesBase64-encoded HMAC-SHA256 secret
IsActivebooleanNoDefault trueActive/inactive toggle
InstalledCapacityWattsdouble precisionYes[0, 1,000,000]Installed panel capacity in watts
Currencyvarchar(3)NoDefault EURISO 4217 currency code
SystemCostnumericYesTotal system installation cost
MaintenanceCostPerYearnumericYesAnnual maintenance cost
InstallationDatetimestamp with time zoneYesSystem installation date
CreatedAttimestamp with time zoneNoDefault UTC NOWCreation timestamp
UpdatedAttimestamp with time zoneNoDefault UTC NOWLast modification timestamp

Relationships:

  • Many-to-One with Users (ON DELETE CASCADE)
  • Many-to-One with PowerGroups (ON DELETE SET NULL)
  • One-to-Many with WeatherData, KwhPriceHistories, SunSourceSharings (all CASCADE)

Indexes: UserId, PowerGroupId


WeatherData

Weather observations and forecasts linked to specific sun sources via geolocation.

ColumnTypeNullableDescription
IduuidNoPrimary key
SunSourceIduuidNoFK → SunSources.Id
Datetimestamp with time zoneNoForecast date
TemperatureMaxdouble precisionYesMaximum temperature (°C)
TemperatureMindouble precisionYesMinimum temperature (°C)
ShortwaveRadiationSumdouble precisionYesDaily solar radiation (MJ/m²)
WeatherCodeintegerYesWMO weather code
UvIndexMaxdouble precisionYesMaximum UV index
PrecipitationSumdouble precisionYesTotal precipitation (mm)
Sunrisetimestamp with time zoneYesSunrise time
Sunsettimestamp with time zoneYesSunset time
CreatedAttimestamp with time zoneNoRecord creation timestamp

Indexes:

  • SunSourceId
  • (SunSourceId, Date)unique (prevents duplicate forecasts)

KwhPriceHistories

Historical electricity pricing used for ROI calculations.

ColumnTypeNullableDescription
IduuidNoPrimary key
SunSourceIduuidNoFK → SunSources.Id
PricePerKwhnumericNoPrice per kilowatt-hour
EffectiveFromtimestamp with time zoneNoDate this price becomes active
CreatedAttimestamp with time zoneNoRecord creation timestamp
UpdatedAttimestamp with time zoneNoLast modification timestamp

Indexes:

  • SunSourceId
  • (SunSourceId, EffectiveFrom) — composite for efficient price lookups by date

SunSourceSharings

Controls public visibility of sun source data for sharing features.

ColumnTypeNullableDefaultDescription
IduuidNoPrimary key
SunSourceIduuidNoFK → SunSources.Id
IsEnabledbooleanNofalseMaster sharing toggle
ShareMonitorbooleanNofalseShare real-time metrics
ShareWeatherbooleanNofalseShare weather data
ShareForecastbooleanNofalseShare ML predictions
ShareReturnsbooleanNofalseShare ROI calculations
CreatedAttimestamp with time zoneNoUTC NOWCreation timestamp
UpdatedAttimestamp with time zoneNoUTC NOWLast modification timestamp

Indexes: SunSourceId (unique — one sharing config per source)


UserSettings

Key-value store for user preferences.

ColumnTypeNullableDescription
IduuidNoPrimary key
UserIdtextNoFK → Users.Id
SettingTypeintegerNoEnum value (see below)
ValuetextNoSetting value as string
UpdatedAttimestamp with time zoneNoLast modification timestamp

Setting Types:

ValueNameDescriptionValid Values
1TemperatureUnitDisplay temperature unit0 (Metric/°C), 1 (Imperial/°F)
2AutoUpdateWeatherDataAuto-refresh weather on schedule0 (disabled), 1 (enabled)
3AutoRunPredictionsAuto-run ML predictions on schedule0 (disabled), 1 (enabled)

Indexes: (UserId, SettingType)unique (one value per setting per user)


ASP.NET Identity Tables

These tables are auto-managed by ASP.NET Identity and should not be modified directly:

TablePurpose
AspNetRolesRole definitions (Overseer, Admin, User)
AspNetUserRolesUser-to-role assignments
AspNetUserClaimsUser claims storage
AspNetRoleClaimsRole claims storage
AspNetUserLoginsExternal login providers
AspNetUserTokensAuthentication tokens

MongoDB — Time-Series Database

Database: ampradb · Driver: MongoDB.Driver (C#) / PyMongo (Python)

Collections

CollectionPurposeIndexed Fields
normalized_sun_source_dataReal-time telemetry data pointssunSourceId, timestamp
predictionsML model prediction outputssunSourceId, createdAt
model_metadataTrained model informationsunSourceId

normalized_sun_source_data

Each document represents a single telemetry snapshot from a solar installation:

FieldBSON TypeDescription
_idObjectIdAuto-generated document ID
sunSourceIdString (GUID)Source identifier
timestampDateTimeMeasurement time (UTC)
Battery Metrics
stateOfChargeDoubleBattery charge level (%)
stateOfHealthDoubleBattery health (%)
batteryVoltageDoubleBattery voltage (V)
batteryCurrentDoubleBattery current (A)
batteryTemperatureDoubleBattery temperature (°C)
batteryCapacityDoubleTotal battery capacity (Ah)
remainingCapacityDoubleRemaining battery capacity (Ah)
Solar Metrics
solarVoltageDoublePV array voltage (V)
solarCurrentDoublePV array current (A)
solarPowerDoublePV production power (W)
Load Metrics
outputVoltageDoubleInverter output voltage (V)
outputCurrentDoubleInverter output current (A)
outputFrequencyDoubleOutput frequency (Hz)
loadPowerDoubleCurrent load consumption (W)
loadPercentageDoubleLoad as % of rated capacity
apparentPowerDoubleApparent power (VA)
Grid Metrics
gridVoltageDoubleGrid voltage (V)
gridCurrentDoubleGrid current (A)
gridFrequencyDoubleGrid frequency (Hz)
Energy Totals
totalEnergyProducedDoubleLifetime energy produced (kWh)
totalEnergyConsumedDoubleLifetime energy consumed (kWh)
dailyEnergyProducedDoubleToday's energy produced (kWh)
dailyEnergyConsumedDoubleToday's energy consumed (kWh)
Status
operatingModeStringCurrent operating mode
deviceStatusStringDevice health status
faultCodesArray<String>Active fault codes
warningCodesArray<String>Active warning codes
Audit
rawDataDocumentOriginal unmodified payload
metadataDocumentKey-value pairs for additional context

Migration History

#MigrationDateChanges
1InitialIdentity2026-02-07ASP.NET Identity tables
2AddEmailVerification2026-02-07Verification code fields on User
3AddLastCodeSentAt2026-02-07Rate limiting for code resend
4AddPowerGroupsAndSunSources2026-02-07Core entity tables
5AddLocationToSunSource2026-02-10Latitude/Longitude fields
6AddLogoUrlToPowerGroup2026-02-11Group branding
7AddWeatherData2026-02-14Weather observations table
8AddUserSettings2026-02-14User preferences table
9AddIconUrlToSunSource2026-02-14Custom source icons
10RemoveProtocolFromSunSource2026-02-21Schema cleanup
11AddInstalledCapacityToSunSource2026-02-23Panel capacity tracking
12AddKwhPriceHistoryAndCurrency2026-02-24ROI pricing model
13AddSunSourceSharing2026-03-01Public sharing feature
14SelfHostedMqtt2026-03-02MQTT credential fields
15PendingModelSync2026-03-06Schema alignment
16PendingChanges2026-03-06Schema alignment
17BusinessLogicAuditOverhaul2026-03-06SystemCost, MaintenanceCost, InstallationDate, PricePerKwh precision