horizon-sdk 9.0.0

Canonical Rust data access layer for the Horizon platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
use chrono::Utc;
use tracing::debug;
use uuid::Uuid;

use crate::types::error::{HorizonError, PostgresError, Result};
use crate::types::filter::BeamgramSpecificationFilter;
use crate::types::model::BeamgramSpecification;
use sqlx::{Postgres, QueryBuilder};

use super::PostgresRepository;

impl PostgresRepository {
    /// Batch-insert beamgram specs (multi-row INSERT) and return their
    /// server-generated ids.
    pub async fn bulk_insert_beamgram_specification(
        &self,
        specs: &[BeamgramSpecification],
    ) -> Result<Vec<Uuid>> {
        const COLUMN_COUNT: usize = 14;
        #[allow(
            clippy::decimal_literal_representation,
            reason = "Integer representation is more readable for this applications"
        )]
        const MAX_PARAMETER_COUNT: usize = 65_535;
        #[allow(
            clippy::integer_division,
            clippy::integer_division_remainder_used,
            reason = "Can only perform whole writes at once"
        )]
        let max_writes = MAX_PARAMETER_COUNT / COLUMN_COUNT;

        let now = Utc::now();

        let mut id_vector = Vec::with_capacity(specs.len());
        for chunk in specs.chunks(max_writes) {
            let mut query_builder: QueryBuilder<Postgres> = QueryBuilder::new(
                "INSERT INTO horizon_public.beamgram_specification \
             (id, center_bearing, center_bin_width, min_frequency, max_frequency, \
              fft_sample_count, organization_id, update_rate, normalizer, name, \
              elevation_increment, lower_elevation, upper_elevation, modified_datetime) ",
            );
            query_builder.push_values(chunk, |mut b, spec| {
                b.push("COALESCE(")
                    .push_bind_unseparated(spec.id)
                    .push_unseparated(", gen_random_uuid())")
                    .push_bind(spec.center_bearing)
                    .push_bind(spec.center_bin_width)
                    .push_bind(spec.min_frequency)
                    .push_bind(spec.max_frequency)
                    .push_bind(spec.fft_sample_count)
                    .push_bind(self.organization_id.or(spec.organization_id))
                    .push_bind(spec.update_rate_ms)
                    .push_unseparated("::bigint * interval '1 millisecond'")
                    .push_bind(spec.normalizer.clone())
                    .push_bind(spec.name.clone())
                    .push_bind(spec.elevation_increment)
                    .push_bind(spec.lower_elevation)
                    .push_bind(spec.upper_elevation)
                    .push_bind(now);
            });
            query_builder.push(" RETURNING id");
            let id_batch: Vec<Uuid> = query_builder
                .build_query_scalar()
                .fetch_all(&self.pool)
                .await?;
            id_vector.extend(id_batch);
        }
        Ok(id_vector)
    }

    /// Delete a beamgram specification by ID. Returns the number of rows removed.
    pub async fn delete_beamgram_specification(&self, id: Uuid) -> Result<u64> {
        let result = sqlx::query!(
            "DELETE FROM horizon_public.beamgram_specification WHERE id = $1",
            id
        )
        .execute(&self.pool)
        .await?;
        Ok(result.rows_affected())
    }

    /// Create a new beamgram specification.
    pub async fn insert_beamgram_specification(
        &self,
        spec: &BeamgramSpecification,
    ) -> Result<BeamgramSpecification> {
        let now = Utc::now();
        let org = self.organization_id.or(spec.organization_id);
        Ok(sqlx::query_as!(
            BeamgramSpecification,
            r#"
            INSERT INTO horizon_public.beamgram_specification
                (id, center_bearing, center_bin_width, elevation_increment,
                 lower_elevation, upper_elevation, max_frequency,
                 min_frequency, name, fft_sample_count, organization_id,
                 update_rate, normalizer, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6, $7, $8, $9, $10, $11,
                    $12::bigint * interval '1 millisecond', $13, $14)
            RETURNING id, created_datetime, modified_datetime, center_bearing,
                      center_bin_width, elevation_increment, lower_elevation,
                      upper_elevation, max_frequency, min_frequency,
                      name, fft_sample_count, organization_id,
                      (EXTRACT(EPOCH FROM update_rate) * 1000)::bigint as "update_rate_ms: i64",
                      normalizer
            "#,
            spec.id,
            spec.center_bearing,
            spec.center_bin_width,
            spec.elevation_increment,
            spec.lower_elevation,
            spec.upper_elevation,
            spec.max_frequency,
            spec.min_frequency,
            spec.name,
            spec.fft_sample_count,
            org,
            spec.update_rate_ms,
            spec.normalizer,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }

    /// Create a batch of beamgram specifications in a single multi-row INSERT.
    ///
    /// Per-column slices are passed to `PostgreSQL` `UNNEST(...)` so the
    /// entire batch becomes one SQL statement and one network round-trip.
    /// Missing IDs are filled by `gen_random_uuid()` server-side, and
    /// `modified_datetime` is set to the same `now()` value for every
    /// row. `update_rate_ms` is converted to a Postgres interval on
    /// write and back to milliseconds on read.
    ///
    /// Returns the inserted rows in input order. Wraps the statement in
    /// a transaction so a per-row failure rolls back the entire batch.
    #[allow(
        clippy::as_conversions,
        reason = "sqlx::query_as! requires `&Vec<T> as &[T]` ascription to bind a nullable Postgres array; conversion direction is unambiguous (same element type)"
    )]
    #[allow(
        clippy::too_many_lines,
        reason = "13-column batch insert: the per-column slice collection plus the order-preserving CTE query is inherently long and reads more clearly inline than split across helpers"
    )]
    pub async fn insert_beamgram_specification_batch(
        &self,
        specs: &[BeamgramSpecification],
    ) -> Result<Vec<BeamgramSpecification>> {
        if specs.is_empty() {
            return Ok(Vec::new());
        }
        let now = Utc::now();
        let ids: Vec<Option<Uuid>> = specs.iter().map(|spec| spec.id).collect();
        let center_bearings: Vec<Option<f64>> =
            specs.iter().map(|spec| spec.center_bearing).collect();
        let center_bin_widths: Vec<Option<f64>> =
            specs.iter().map(|spec| spec.center_bin_width).collect();
        let elevation_increments: Vec<Option<f64>> =
            specs.iter().map(|spec| spec.elevation_increment).collect();
        let lower_elevations: Vec<Option<f64>> =
            specs.iter().map(|spec| spec.lower_elevation).collect();
        let upper_elevations: Vec<Option<f64>> =
            specs.iter().map(|spec| spec.upper_elevation).collect();
        let max_frequencies: Vec<Option<f64>> =
            specs.iter().map(|spec| spec.max_frequency).collect();
        let min_frequencies: Vec<Option<f64>> =
            specs.iter().map(|spec| spec.min_frequency).collect();
        let names: Vec<Option<String>> = specs.iter().map(|spec| spec.name.clone()).collect();
        let fft_sample_counts: Vec<Option<i32>> =
            specs.iter().map(|spec| spec.fft_sample_count).collect();
        let orgs: Vec<Option<Uuid>> = specs
            .iter()
            .map(|spec| self.organization_id.or(spec.organization_id))
            .collect();
        let update_rate_ms_list: Vec<Option<i64>> =
            specs.iter().map(|spec| spec.update_rate_ms).collect();
        let normalizers: Vec<Option<String>> =
            specs.iter().map(|spec| spec.normalizer.clone()).collect();
        let mut tx = self.pool.begin().await?;
        let rows = sqlx::query_as!(
            BeamgramSpecification,
            r#"
            WITH source AS (
                SELECT
                    COALESCE(id, gen_random_uuid()) AS id,
                    center_bearing, center_bin_width, elevation_increment,
                    lower_elevation, upper_elevation, max_frequency,
                    min_frequency, name, fft_sample_count, organization_id,
                    update_rate_ms, normalizer, ord
                FROM UNNEST(
                    $1::uuid[], $2::float8[], $3::float8[], $4::float8[],
                    $5::float8[], $6::float8[], $7::float8[], $8::float8[],
                    $9::text[], $10::integer[], $11::uuid[], $12::bigint[],
                    $13::text[]
                ) WITH ORDINALITY
                    AS batch(id, center_bearing, center_bin_width, elevation_increment,
                             lower_elevation, upper_elevation, max_frequency,
                             min_frequency, name, fft_sample_count, organization_id,
                             update_rate_ms, normalizer, ord)
            ),
            inserted AS (
                INSERT INTO horizon_public.beamgram_specification
                    (id, center_bearing, center_bin_width, elevation_increment,
                     lower_elevation, upper_elevation, max_frequency,
                     min_frequency, name, fft_sample_count, organization_id,
                     update_rate, normalizer, modified_datetime)
                SELECT
                    id, center_bearing, center_bin_width, elevation_increment,
                    lower_elevation, upper_elevation, max_frequency,
                    min_frequency, name, fft_sample_count, organization_id,
                    update_rate_ms * interval '1 millisecond',
                    normalizer, $14
                FROM source
                RETURNING id, created_datetime, modified_datetime, center_bearing,
                          center_bin_width, elevation_increment, lower_elevation,
                          upper_elevation, max_frequency, min_frequency,
                          name, fft_sample_count, organization_id, update_rate, normalizer
            )
            SELECT inserted.id, inserted.created_datetime, inserted.modified_datetime,
                   inserted.center_bearing, inserted.center_bin_width,
                   inserted.elevation_increment, inserted.lower_elevation,
                   inserted.upper_elevation, inserted.max_frequency, inserted.min_frequency,
                   inserted.name, inserted.fft_sample_count, inserted.organization_id,
                   (EXTRACT(EPOCH FROM inserted.update_rate) * 1000)::bigint as "update_rate_ms: i64",
                   inserted.normalizer
            FROM inserted
            JOIN source ON source.id = inserted.id
            ORDER BY source.ord
            "#,
            &ids as &[Option<Uuid>],
            &center_bearings as &[Option<f64>],
            &center_bin_widths as &[Option<f64>],
            &elevation_increments as &[Option<f64>],
            &lower_elevations as &[Option<f64>],
            &upper_elevations as &[Option<f64>],
            &max_frequencies as &[Option<f64>],
            &min_frequencies as &[Option<f64>],
            &names as &[Option<String>],
            &fft_sample_counts as &[Option<i32>],
            &orgs as &[Option<Uuid>],
            &update_rate_ms_list as &[Option<i64>],
            &normalizers as &[Option<String>],
            now,
        )
        .fetch_all(&mut *tx)
        .await?;
        tx.commit().await?;
        debug!(
            batch_size = rows.len(),
            "insert_beamgram_specification_batch"
        );
        Ok(rows)
    }

    /// List beamgram specification records matching every set filter field.
    pub async fn list_beamgram_specifications(
        &self,
        filter: &BeamgramSpecificationFilter,
    ) -> Result<Vec<BeamgramSpecification>> {
        Ok(sqlx::query_as!(
            BeamgramSpecification,
            r#"
            SELECT id, created_datetime, modified_datetime, center_bearing,
                   center_bin_width, elevation_increment, lower_elevation,
                   upper_elevation, max_frequency, min_frequency,
                   name, fft_sample_count, organization_id,
                   (EXTRACT(EPOCH FROM update_rate) * 1000)::bigint as "update_rate_ms: i64",
                   normalizer
            FROM horizon_public.beamgram_specification
            WHERE ($1::float8 IS NULL OR center_bearing = $1)
              AND ($2::float8 IS NULL OR center_bin_width = $2)
              AND ($3::float8 IS NULL OR elevation_increment = $3)
              AND ($4::integer IS NULL OR fft_sample_count = $4)
              AND ($5::float8 IS NULL OR lower_elevation = $5)
              AND ($6::float8 IS NULL OR max_frequency = $6)
              AND ($7::float8 IS NULL OR min_frequency = $7)
              AND ($8::text IS NULL OR name = $8)
              AND ($9::text IS NULL OR normalizer = $9)
              AND ($10::uuid IS NULL OR organization_id = $10)
              AND ($11::bigint IS NULL OR update_rate = $11 * interval '1 millisecond')
              AND ($12::float8 IS NULL OR upper_elevation = $12)
            "#,
            filter.center_bearing,
            filter.center_bin_width,
            filter.elevation_increment,
            filter.fft_sample_count,
            filter.lower_elevation,
            filter.max_frequency,
            filter.min_frequency,
            filter.name,
            filter.normalizer,
            filter.organization_id,
            filter.update_rate_ms,
            filter.upper_elevation,
        )
        .fetch_all(&self.pool)
        .await?)
    }

    /// Read a beamgram specification by ID.
    pub async fn read_beamgram_specification(
        &self,
        id: Uuid,
    ) -> Result<Option<BeamgramSpecification>> {
        Ok(sqlx::query_as!(
            BeamgramSpecification,
            r#"
            SELECT id, created_datetime, modified_datetime, center_bearing,
                   center_bin_width, elevation_increment, lower_elevation,
                   upper_elevation, max_frequency, min_frequency,
                   name, fft_sample_count, organization_id,
                   (EXTRACT(EPOCH FROM update_rate) * 1000)::bigint as "update_rate_ms: i64",
                   normalizer
            FROM horizon_public.beamgram_specification WHERE id = $1
            "#,
            id,
        )
        .fetch_optional(&self.pool)
        .await?)
    }

    /// Update an existing beamgram specification by ID.
    ///
    /// Returns `HorizonError::Postgres(PostgresError::NotFound)` if no row
    /// with the given ID exists. Matches Python `BaseRepository.update()`
    /// semantics. `update_rate_ms` is converted to a Postgres interval on
    /// write and back to milliseconds on read.
    pub async fn update_beamgram_specification(
        &self,
        spec: &BeamgramSpecification,
    ) -> Result<BeamgramSpecification> {
        let now = Utc::now();
        let org = self.organization_id.or(spec.organization_id);
        let result = sqlx::query_as!(
            BeamgramSpecification,
            r#"
            UPDATE horizon_public.beamgram_specification
            SET
                center_bearing = $2,
                center_bin_width = $3,
                elevation_increment = $4,
                lower_elevation = $5,
                upper_elevation = $6,
                max_frequency = $7,
                min_frequency = $8,
                name = $9,
                fft_sample_count = $10,
                organization_id = $11,
                update_rate = $12::bigint * interval '1 millisecond',
                normalizer = $13,
                modified_datetime = $14
            WHERE id = $1
            RETURNING id, created_datetime, modified_datetime, center_bearing,
                      center_bin_width, elevation_increment, lower_elevation,
                      upper_elevation, max_frequency, min_frequency,
                      name, fft_sample_count, organization_id,
                      (EXTRACT(EPOCH FROM update_rate) * 1000)::bigint as "update_rate_ms: i64",
                      normalizer
            "#,
            spec.id,
            spec.center_bearing,
            spec.center_bin_width,
            spec.elevation_increment,
            spec.lower_elevation,
            spec.upper_elevation,
            spec.max_frequency,
            spec.min_frequency,
            spec.name,
            spec.fft_sample_count,
            org,
            spec.update_rate_ms,
            spec.normalizer,
            now,
        )
        .fetch_optional(&self.pool)
        .await?;

        result.ok_or_else(|| {
            HorizonError::Postgres(PostgresError::NotFound {
                entity: "beamgram_specification".to_owned(),
                id: spec.id.into(),
            })
        })
    }

    /// Insert a beamgram specification or update it if a row with the same
    /// ID already exists. `update_rate_ms` is converted to a Postgres
    /// interval on write and back to milliseconds on read.
    pub async fn upsert_beamgram_specification(
        &self,
        spec: &BeamgramSpecification,
    ) -> Result<BeamgramSpecification> {
        let now = Utc::now();
        let org = self.organization_id.or(spec.organization_id);
        Ok(sqlx::query_as!(
            BeamgramSpecification,
            r#"
            INSERT INTO horizon_public.beamgram_specification
                (id, center_bearing, center_bin_width, elevation_increment,
                 lower_elevation, upper_elevation, max_frequency,
                 min_frequency, name, fft_sample_count, organization_id,
                 update_rate, normalizer, modified_datetime)
            VALUES (COALESCE($1, gen_random_uuid()), $2, $3, $4, $5, $6, $7, $8, $9, $10, $11,
                    $12::bigint * interval '1 millisecond', $13, $14)
            ON CONFLICT (id) DO UPDATE SET
                center_bearing = EXCLUDED.center_bearing,
                center_bin_width = EXCLUDED.center_bin_width,
                elevation_increment = EXCLUDED.elevation_increment,
                lower_elevation = EXCLUDED.lower_elevation,
                upper_elevation = EXCLUDED.upper_elevation,
                max_frequency = EXCLUDED.max_frequency,
                min_frequency = EXCLUDED.min_frequency,
                name = EXCLUDED.name, fft_sample_count = EXCLUDED.fft_sample_count,
                organization_id = EXCLUDED.organization_id,
                update_rate = EXCLUDED.update_rate,
                normalizer = EXCLUDED.normalizer,
                modified_datetime = EXCLUDED.modified_datetime
            RETURNING id, created_datetime, modified_datetime, center_bearing,
                      center_bin_width, elevation_increment, lower_elevation,
                      upper_elevation, max_frequency, min_frequency,
                      name, fft_sample_count, organization_id,
                      (EXTRACT(EPOCH FROM update_rate) * 1000)::bigint as "update_rate_ms: i64",
                      normalizer
            "#,
            spec.id,
            spec.center_bearing,
            spec.center_bin_width,
            spec.elevation_increment,
            spec.lower_elevation,
            spec.upper_elevation,
            spec.max_frequency,
            spec.min_frequency,
            spec.name,
            spec.fft_sample_count,
            org,
            spec.update_rate_ms,
            spec.normalizer,
            now,
        )
        .fetch_one(&self.pool)
        .await?)
    }
}