-
Notifications
You must be signed in to change notification settings - Fork 230
/
sqlspec.go
838 lines (798 loc) · 26 KB
/
sqlspec.go
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
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
// Copyright 2021-present The Atlas Authors. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package postgres
import (
"fmt"
"reflect"
"strconv"
"strings"
"ariga.io/atlas/schemahcl"
"ariga.io/atlas/sql/internal/specutil"
"ariga.io/atlas/sql/internal/sqlx"
"ariga.io/atlas/sql/postgres/internal/postgresop"
"ariga.io/atlas/sql/schema"
"ariga.io/atlas/sql/sqlspec"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/zclconf/go-cty/cty"
)
type (
doc struct {
Tables []*sqlspec.Table `spec:"table"`
Enums []*Enum `spec:"enum"`
Schemas []*sqlspec.Schema `spec:"schema"`
}
// Enum holds a specification for an enum, that can be referenced as a column type.
Enum struct {
Name string `spec:",name"`
Schema *schemahcl.Ref `spec:"schema"`
Values []string `spec:"values"`
schemahcl.DefaultExtension
}
)
func init() {
schemahcl.Register("enum", &Enum{})
}
// evalSpec evaluates an Atlas DDL document into v using the input.
func evalSpec(p *hclparse.Parser, v any, input map[string]cty.Value) error {
switch v := v.(type) {
case *schema.Realm:
var d doc
if err := hclState.Eval(p, &d, input); err != nil {
return err
}
if err := specutil.Scan(v, d.Schemas, d.Tables, convertTable); err != nil {
return fmt.Errorf("specutil: failed converting to *schema.Realm: %w", err)
}
if len(d.Enums) > 0 {
if err := convertEnums(d.Tables, d.Enums, v); err != nil {
return err
}
}
case *schema.Schema:
var d doc
if err := hclState.Eval(p, &d, input); err != nil {
return err
}
if len(d.Schemas) != 1 {
return fmt.Errorf("specutil: expecting document to contain a single schema, got %d", len(d.Schemas))
}
r := &schema.Realm{}
if err := specutil.Scan(r, d.Schemas, d.Tables, convertTable); err != nil {
return err
}
if err := convertEnums(d.Tables, d.Enums, r); err != nil {
return err
}
*v = *r.Schemas[0]
case schema.Schema, schema.Realm:
return fmt.Errorf("postgres: Eval expects a pointer: received %[1]T, expected *%[1]T", v)
default:
return hclState.Eval(p, v, input)
}
return nil
}
// MarshalSpec marshals v into an Atlas DDL document using a schemahcl.Marshaler.
func MarshalSpec(v any, marshaler schemahcl.Marshaler) ([]byte, error) {
var d doc
switch s := v.(type) {
case *schema.Schema:
var err error
doc, err := schemaSpec(s)
if err != nil {
return nil, fmt.Errorf("specutil: failed converting schema to spec: %w", err)
}
d.Tables = doc.Tables
d.Schemas = doc.Schemas
d.Enums = doc.Enums
case *schema.Realm:
for _, s := range s.Schemas {
doc, err := schemaSpec(s)
if err != nil {
return nil, fmt.Errorf("specutil: failed converting schema to spec: %w", err)
}
d.Tables = append(d.Tables, doc.Tables...)
d.Schemas = append(d.Schemas, doc.Schemas...)
d.Enums = append(d.Enums, doc.Enums...)
}
if err := specutil.QualifyDuplicates(d.Tables); err != nil {
return nil, err
}
if err := specutil.QualifyReferences(d.Tables, s); err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("specutil: failed marshaling spec. %T is not supported", v)
}
return marshaler.MarshalSpec(&d)
}
var (
hclState = schemahcl.New(
schemahcl.WithTypes("table.column.type", TypeRegistry.Specs()),
schemahcl.WithScopedEnums("table.index.type", IndexTypeBTree, IndexTypeBRIN, IndexTypeHash, IndexTypeGIN, IndexTypeGiST, "GiST", IndexTypeSPGiST, "SPGiST"),
schemahcl.WithScopedEnums("table.partition.type", PartitionTypeRange, PartitionTypeList, PartitionTypeHash),
schemahcl.WithScopedEnums("table.column.identity.generated", GeneratedTypeAlways, GeneratedTypeByDefault),
schemahcl.WithScopedEnums("table.column.as.type", "STORED"),
schemahcl.WithScopedEnums("table.foreign_key.on_update", specutil.ReferenceVars...),
schemahcl.WithScopedEnums("table.foreign_key.on_delete", specutil.ReferenceVars...),
schemahcl.WithScopedEnums("table.index.on.ops", func() (ops []string) {
for _, op := range postgresop.Classes {
ops = append(ops, op.Name)
}
return ops
}()...),
)
// MarshalHCL marshals v into an Atlas HCL DDL document.
MarshalHCL = schemahcl.MarshalerFunc(func(v any) ([]byte, error) {
return MarshalSpec(v, hclState)
})
// EvalHCL implements the schemahcl.Evaluator interface.
EvalHCL = schemahcl.EvalFunc(evalSpec)
// EvalHCLBytes is a helper that evaluates an HCL document from a byte slice instead
// of from an hclparse.Parser instance.
EvalHCLBytes = specutil.HCLBytesFunc(EvalHCL)
)
// convertTable converts a sqlspec.Table to a schema.Table. Table conversion is done without converting
// ForeignKeySpecs into ForeignKeys, as the target tables do not necessarily exist in the schema
// at this point. Instead, the linking is done by the convertSchema function.
func convertTable(spec *sqlspec.Table, parent *schema.Schema) (*schema.Table, error) {
t, err := specutil.Table(spec, parent, convertColumn, convertPK, convertIndex, specutil.Check)
if err != nil {
return nil, err
}
if err := convertPartition(spec.Extra, t); err != nil {
return nil, err
}
return t, nil
}
// convertPartition converts and appends the partition block into the table attributes if exists.
func convertPartition(spec schemahcl.Resource, table *schema.Table) error {
r, ok := spec.Resource("partition")
if !ok {
return nil
}
var p struct {
Type string `spec:"type"`
Columns []*schemahcl.Ref `spec:"columns"`
Parts []*struct {
Expr string `spec:"expr"`
Column *schemahcl.Ref `spec:"column"`
} `spec:"by"`
}
if err := r.As(&p); err != nil {
return fmt.Errorf("parsing %s.partition: %w", table.Name, err)
}
if p.Type == "" {
return fmt.Errorf("missing attribute %s.partition.type", table.Name)
}
key := &Partition{T: p.Type}
switch n, m := len(p.Columns), len(p.Parts); {
case n == 0 && m == 0:
return fmt.Errorf("missing columns or expressions for %s.partition", table.Name)
case n > 0 && m > 0:
return fmt.Errorf(`multiple definitions for %s.partition, use "columns" or "by"`, table.Name)
case n > 0:
for _, r := range p.Columns {
c, err := specutil.ColumnByRef(table, r)
if err != nil {
return err
}
key.Parts = append(key.Parts, &PartitionPart{C: c})
}
case m > 0:
for i, p := range p.Parts {
switch {
case p.Column == nil && p.Expr == "":
return fmt.Errorf("missing column or expression for %s.partition.by at position %d", table.Name, i)
case p.Column != nil && p.Expr != "":
return fmt.Errorf("multiple definitions for %s.partition.by at position %d", table.Name, i)
case p.Column != nil:
c, err := specutil.ColumnByRef(table, p.Column)
if err != nil {
return err
}
key.Parts = append(key.Parts, &PartitionPart{C: c})
case p.Expr != "":
key.Parts = append(key.Parts, &PartitionPart{X: &schema.RawExpr{X: p.Expr}})
}
}
}
table.AddAttrs(key)
return nil
}
// fromPartition returns the resource spec for representing the partition block.
func fromPartition(p Partition) *schemahcl.Resource {
key := &schemahcl.Resource{
Type: "partition",
Attrs: []*schemahcl.Attr{
specutil.VarAttr("type", strings.ToUpper(specutil.Var(p.T))),
},
}
columns, ok := func() ([]*schemahcl.Ref, bool) {
parts := make([]*schemahcl.Ref, 0, len(p.Parts))
for _, p := range p.Parts {
if p.C == nil {
return nil, false
}
parts = append(parts, specutil.ColumnRef(p.C.Name))
}
return parts, true
}()
if ok {
key.Attrs = append(key.Attrs, schemahcl.RefsAttr("columns", columns...))
return key
}
for _, p := range p.Parts {
part := &schemahcl.Resource{Type: "by"}
switch {
case p.C != nil:
part.Attrs = append(part.Attrs, schemahcl.RefAttr("column", specutil.ColumnRef(p.C.Name)))
case p.X != nil:
part.Attrs = append(part.Attrs, schemahcl.StringAttr("expr", p.X.(*schema.RawExpr).X))
}
key.Children = append(key.Children, part)
}
return key
}
// convertColumn converts a sqlspec.Column into a schema.Column.
func convertColumn(spec *sqlspec.Column, _ *schema.Table) (*schema.Column, error) {
if err := fixDefaultQuotes(spec); err != nil {
return nil, err
}
c, err := specutil.Column(spec, convertColumnType)
if err != nil {
return nil, err
}
if r, ok := spec.Extra.Resource("identity"); ok {
id, err := convertIdentity(r)
if err != nil {
return nil, err
}
c.Attrs = append(c.Attrs, id)
}
if err := specutil.ConvertGenExpr(spec.Remain(), c, generatedType); err != nil {
return nil, err
}
return c, nil
}
func convertIdentity(r *schemahcl.Resource) (*Identity, error) {
var spec struct {
Generation string `spec:"generated"`
Start int64 `spec:"start"`
Increment int64 `spec:"increment"`
}
if err := r.As(&spec); err != nil {
return nil, err
}
id := &Identity{Generation: specutil.FromVar(spec.Generation), Sequence: &Sequence{}}
if spec.Start != 0 {
id.Sequence.Start = spec.Start
}
if spec.Increment != 0 {
id.Sequence.Increment = spec.Increment
}
return id, nil
}
// fixDefaultQuotes fixes the quotes on the Default field to be single quotes
// instead of double quotes.
func fixDefaultQuotes(spec *sqlspec.Column) error {
if spec.Default.Type() != cty.String {
return nil
}
if s := spec.Default.AsString(); sqlx.IsQuoted(s, '"') {
uq, err := strconv.Unquote(s)
if err != nil {
return err
}
s = "'" + uq + "'"
spec.Default = cty.StringVal(s)
}
return nil
}
// convertPK converts a sqlspec.PrimaryKey into a schema.Index.
func convertPK(spec *sqlspec.PrimaryKey, parent *schema.Table) (*schema.Index, error) {
idx, err := specutil.PrimaryKey(spec, parent)
if err != nil {
return nil, err
}
if err := convertIndexPK(spec, parent, idx); err != nil {
return nil, err
}
return idx, nil
}
// convertIndex converts a sqlspec.Index into a schema.Index.
func convertIndex(spec *sqlspec.Index, t *schema.Table) (*schema.Index, error) {
idx, err := specutil.Index(spec, t, convertPart)
if err != nil {
return nil, err
}
if attr, ok := spec.Attr("type"); ok {
t, err := attr.String()
if err != nil {
return nil, err
}
idx.Attrs = append(idx.Attrs, &IndexType{T: strings.ToUpper(t)})
}
if attr, ok := spec.Attr("where"); ok {
p, err := attr.String()
if err != nil {
return nil, err
}
idx.Attrs = append(idx.Attrs, &IndexPredicate{P: p})
}
if err := convertIndexPK(spec, t, idx); err != nil {
return nil, err
}
return idx, nil
}
// convertIndexPK converts the index parameters shared between primary and secondary indexes.
func convertIndexPK(spec specutil.Attrer, t *schema.Table, idx *schema.Index) error {
if attr, ok := spec.Attr("page_per_range"); ok {
p, err := attr.Int64()
if err != nil {
return err
}
idx.Attrs = append(idx.Attrs, &IndexStorageParams{PagesPerRange: p})
}
if attr, ok := spec.Attr("include"); ok {
refs, err := attr.Refs()
if err != nil {
return err
}
if len(refs) == 0 {
return fmt.Errorf("unexpected empty INCLUDE in index %q definition", idx.Name)
}
include := make([]*schema.Column, len(refs))
for i, r := range refs {
if include[i], err = specutil.ColumnByRef(t, r); err != nil {
return err
}
}
idx.Attrs = append(idx.Attrs, &IndexInclude{Columns: include})
}
return nil
}
func convertPart(spec *sqlspec.IndexPart, part *schema.IndexPart) error {
switch opc, ok := spec.Attr("ops"); {
case !ok:
case opc.IsRawExpr():
expr, err := opc.RawExpr()
if err != nil {
return err
}
var op IndexOpClass
if err := op.UnmarshalText([]byte(expr.X)); err != nil {
return fmt.Errorf("unexpected index.on.ops expression %q: %w", expr.X, err)
}
if op.Name != "" {
part.Attrs = append(part.Attrs, &op)
}
case opc.IsRef():
name, err := opc.Ref()
if err != nil {
return err
}
part.Attrs = append(part.Attrs, &IndexOpClass{Name: name})
default:
name, err := opc.String()
if err != nil {
return err
}
part.Attrs = append(part.Attrs, &IndexOpClass{Name: name})
}
return nil
}
const defaultTimePrecision = 6
// convertColumnType converts a sqlspec.Column into a concrete Postgres schema.Type.
func convertColumnType(spec *sqlspec.Column) (schema.Type, error) {
typ, err := TypeRegistry.Type(spec.Type, spec.Extra.Attrs)
if err != nil {
return nil, err
}
// Handle default values for time precision types.
if t, ok := typ.(*schema.TimeType); ok && strings.HasPrefix(t.T, "time") {
if _, ok := attr(spec.Type, "precision"); !ok {
p := defaultTimePrecision
t.Precision = &p
}
}
return typ, nil
}
// convertEnums converts possibly referenced column types (like enums) to
// an actual schema.Type and sets it on the correct schema.Column.
func convertEnums(tables []*sqlspec.Table, enums []*Enum, r *schema.Realm) error {
var (
used = make(map[*Enum]struct{})
byName = make(map[string]*Enum)
)
for _, e := range enums {
byName[e.Name] = e
}
for _, t := range tables {
for _, c := range t.Columns {
var enum *Enum
switch {
case c.Type.IsRef:
n, err := enumName(c.Type)
if err != nil {
return err
}
e, ok := byName[n]
if !ok {
return fmt.Errorf("enum %q was not found", n)
}
enum = e
default:
n, ok := arrayType(c.Type.T)
if !ok || byName[n] == nil {
continue
}
enum = byName[n]
}
used[enum] = struct{}{}
schemaE, err := specutil.SchemaName(enum.Schema)
if err != nil {
return fmt.Errorf("extract schema name from enum refrence: %w", err)
}
es, ok := r.Schema(schemaE)
if !ok {
return fmt.Errorf("schema %q not found in realm for table %q", schemaE, t.Name)
}
schemaT, err := specutil.SchemaName(t.Schema)
if err != nil {
return fmt.Errorf("extract schema name from table refrence: %w", err)
}
ts, ok := r.Schema(schemaT)
if !ok {
return fmt.Errorf("schema %q not found in realm for table %q", schemaT, t.Name)
}
tt, ok := ts.Table(t.Name)
if !ok {
return fmt.Errorf("table %q not found in schema %q", t.Name, ts.Name)
}
cc, ok := tt.Column(c.Name)
if !ok {
return fmt.Errorf("column %q not found in table %q", c.Name, t.Name)
}
e := &schema.EnumType{T: enum.Name, Schema: es, Values: enum.Values}
switch t := cc.Type.Type.(type) {
case *ArrayType:
t.Type = e
default:
cc.Type.Type = e
}
}
}
for _, e := range enums {
if _, ok := used[e]; !ok {
return fmt.Errorf("enum %q declared but not used", e.Name)
}
}
return nil
}
// enumName extracts the name of the referenced Enum from the reference string.
func enumName(ref *schemahcl.Type) (string, error) {
s := strings.Split(ref.T, "$enum.")
if len(s) != 2 {
return "", fmt.Errorf("postgres: failed to extract enum name from %q", ref.T)
}
return s[1], nil
}
// enumRef returns a reference string to the given enum name.
func enumRef(n string) *schemahcl.Ref {
return &schemahcl.Ref{
V: "$enum." + n,
}
}
// schemaSpec converts from a concrete Postgres schema to Atlas specification.
func schemaSpec(schem *schema.Schema) (*doc, error) {
s, tbls, err := specutil.FromSchema(schem, tableSpec)
if err != nil {
return nil, err
}
d := &doc{
Tables: tbls,
Schemas: []*sqlspec.Schema{s},
}
enums := make(map[string]bool)
for _, t := range schem.Tables {
for _, c := range t.Columns {
if e, ok := hasEnumType(c); ok && !enums[e.T] {
d.Enums = append(d.Enums, &Enum{
Name: e.T,
Schema: specutil.SchemaRef(s.Name),
Values: e.Values,
})
enums[e.T] = true
}
}
}
return d, nil
}
// tableSpec converts from a concrete Postgres sqlspec.Table to a schema.Table.
func tableSpec(table *schema.Table) (*sqlspec.Table, error) {
spec, err := specutil.FromTable(
table,
columnSpec,
pkSpec,
indexSpec,
specutil.FromForeignKey,
specutil.FromCheck,
)
if err != nil {
return nil, err
}
if p := (Partition{}); sqlx.Has(table.Attrs, &p) {
spec.Extra.Children = append(spec.Extra.Children, fromPartition(p))
}
return spec, nil
}
func pkSpec(idx *schema.Index) (*sqlspec.PrimaryKey, error) {
spec, err := specutil.FromPrimaryKey(idx)
if err != nil {
return nil, err
}
spec.Extra.Attrs = indexPKSpec(idx, spec.Extra.Attrs)
return spec, nil
}
func indexSpec(idx *schema.Index) (*sqlspec.Index, error) {
spec, err := specutil.FromIndex(idx, partAttr)
if err != nil {
return nil, err
}
// Avoid printing the index type if it is the default.
if i := (IndexType{}); sqlx.Has(idx.Attrs, &i) && strings.ToUpper(i.T) != IndexTypeBTree {
spec.Extra.Attrs = append(spec.Extra.Attrs, specutil.VarAttr("type", strings.ToUpper(i.T)))
}
if i := (IndexPredicate{}); sqlx.Has(idx.Attrs, &i) && i.P != "" {
spec.Extra.Attrs = append(spec.Extra.Attrs, specutil.VarAttr("where", strconv.Quote(i.P)))
}
spec.Extra.Attrs = indexPKSpec(idx, spec.Extra.Attrs)
return spec, nil
}
func indexPKSpec(idx *schema.Index, attrs []*schemahcl.Attr) []*schemahcl.Attr {
if i := (IndexInclude{}); sqlx.Has(idx.Attrs, &i) && len(i.Columns) > 0 {
refs := make([]*schemahcl.Ref, 0, len(i.Columns))
for _, c := range i.Columns {
refs = append(refs, specutil.ColumnRef(c.Name))
}
attrs = append(attrs, schemahcl.RefsAttr("include", refs...))
}
if p, ok := indexStorageParams(idx.Attrs); ok {
attrs = append(attrs, schemahcl.Int64Attr("page_per_range", p.PagesPerRange))
}
return attrs
}
func partAttr(idx *schema.Index, part *schema.IndexPart, spec *sqlspec.IndexPart) error {
var op IndexOpClass
if !sqlx.Has(part.Attrs, &op) {
return nil
}
switch d, err := op.DefaultFor(idx, part); {
case err != nil:
return err
case d:
case len(op.Params) > 0:
spec.Extra.Attrs = append(spec.Extra.Attrs, schemahcl.RawAttr("ops", op.String()))
default:
spec.Extra.Attrs = append(spec.Extra.Attrs, specutil.VarAttr("ops", op.String()))
}
return nil
}
// columnSpec converts from a concrete Postgres schema.Column into a sqlspec.Column.
func columnSpec(c *schema.Column, _ *schema.Table) (*sqlspec.Column, error) {
s, err := specutil.FromColumn(c, columnTypeSpec)
if err != nil {
return nil, err
}
if i := (&Identity{}); sqlx.Has(c.Attrs, i) {
s.Extra.Children = append(s.Extra.Children, fromIdentity(i))
}
if x := (schema.GeneratedExpr{}); sqlx.Has(c.Attrs, &x) {
s.Extra.Children = append(s.Extra.Children, specutil.FromGenExpr(x, generatedType))
}
return s, nil
}
// fromIdentity returns the resource spec for representing the identity attributes.
func fromIdentity(i *Identity) *schemahcl.Resource {
id := &schemahcl.Resource{
Type: "identity",
Attrs: []*schemahcl.Attr{
specutil.VarAttr("generated", strings.ToUpper(specutil.Var(i.Generation))),
},
}
if s := i.Sequence; s != nil {
if s.Start != 1 {
id.Attrs = append(id.Attrs, schemahcl.Int64Attr("start", s.Start))
}
if s.Increment != 1 {
id.Attrs = append(id.Attrs, schemahcl.Int64Attr("increment", s.Increment))
}
}
return id
}
// columnTypeSpec converts from a concrete Postgres schema.Type into sqlspec.Column Type.
func columnTypeSpec(t schema.Type) (*sqlspec.Column, error) {
// Handle postgres enum types. They cannot be put into the TypeRegistry since their name is dynamic.
if e, ok := t.(*schema.EnumType); ok {
return &sqlspec.Column{Type: &schemahcl.Type{
T: enumRef(e.T).V,
IsRef: true,
}}, nil
}
st, err := TypeRegistry.Convert(t)
if err != nil {
return nil, err
}
return &sqlspec.Column{Type: st}, nil
}
// TypeRegistry contains the supported TypeSpecs for the Postgres driver.
var TypeRegistry = schemahcl.NewRegistry(
schemahcl.WithSpecFunc(typeSpec),
schemahcl.WithParser(ParseType),
schemahcl.WithSpecs(
schemahcl.NewTypeSpec(TypeBit, schemahcl.WithAttributes(&schemahcl.TypeAttr{Name: "len", Kind: reflect.Int64})),
schemahcl.AliasTypeSpec("bit_varying", TypeBitVar, schemahcl.WithAttributes(&schemahcl.TypeAttr{Name: "len", Kind: reflect.Int64})),
schemahcl.NewTypeSpec(TypeVarChar, schemahcl.WithAttributes(schemahcl.SizeTypeAttr(false))),
schemahcl.AliasTypeSpec("character_varying", TypeCharVar, schemahcl.WithAttributes(schemahcl.SizeTypeAttr(false))),
schemahcl.NewTypeSpec(TypeChar, schemahcl.WithAttributes(schemahcl.SizeTypeAttr(false))),
schemahcl.NewTypeSpec(TypeCharacter, schemahcl.WithAttributes(schemahcl.SizeTypeAttr(false))),
schemahcl.NewTypeSpec(TypeInt2),
schemahcl.NewTypeSpec(TypeInt4),
schemahcl.NewTypeSpec(TypeInt8),
schemahcl.NewTypeSpec(TypeInt),
schemahcl.NewTypeSpec(TypeInteger),
schemahcl.NewTypeSpec(TypeSmallInt),
schemahcl.NewTypeSpec(TypeBigInt),
schemahcl.NewTypeSpec(TypeText),
schemahcl.NewTypeSpec(TypeBoolean),
schemahcl.NewTypeSpec(TypeBool),
schemahcl.NewTypeSpec(TypeBytea),
schemahcl.NewTypeSpec(TypeCIDR),
schemahcl.NewTypeSpec(TypeInet),
schemahcl.NewTypeSpec(TypeMACAddr),
schemahcl.NewTypeSpec(TypeMACAddr8),
schemahcl.NewTypeSpec(TypeCircle),
schemahcl.NewTypeSpec(TypeLine),
schemahcl.NewTypeSpec(TypeLseg),
schemahcl.NewTypeSpec(TypeBox),
schemahcl.NewTypeSpec(TypePath),
schemahcl.NewTypeSpec(TypePoint),
schemahcl.NewTypeSpec(TypePolygon),
schemahcl.NewTypeSpec(TypeDate),
schemahcl.NewTypeSpec(TypeTime, schemahcl.WithAttributes(precisionTypeAttr()), formatTime()),
schemahcl.NewTypeSpec(TypeTimeTZ, schemahcl.WithAttributes(precisionTypeAttr()), formatTime()),
schemahcl.NewTypeSpec(TypeTimestampTZ, schemahcl.WithAttributes(precisionTypeAttr()), formatTime()),
schemahcl.NewTypeSpec(TypeTimestamp, schemahcl.WithAttributes(precisionTypeAttr()), formatTime()),
schemahcl.AliasTypeSpec("double_precision", TypeDouble),
schemahcl.NewTypeSpec(TypeReal),
schemahcl.NewTypeSpec(TypeFloat, schemahcl.WithAttributes(precisionTypeAttr())),
schemahcl.NewTypeSpec(TypeFloat8),
schemahcl.NewTypeSpec(TypeFloat4),
schemahcl.NewTypeSpec(TypeNumeric, schemahcl.WithAttributes(precisionTypeAttr(), &schemahcl.TypeAttr{Name: "scale", Kind: reflect.Int, Required: false})),
schemahcl.NewTypeSpec(TypeDecimal, schemahcl.WithAttributes(precisionTypeAttr(), &schemahcl.TypeAttr{Name: "scale", Kind: reflect.Int, Required: false})),
schemahcl.NewTypeSpec(TypeSmallSerial),
schemahcl.NewTypeSpec(TypeSerial),
schemahcl.NewTypeSpec(TypeBigSerial),
schemahcl.NewTypeSpec(TypeSerial2),
schemahcl.NewTypeSpec(TypeSerial4),
schemahcl.NewTypeSpec(TypeSerial8),
schemahcl.NewTypeSpec(TypeXML),
schemahcl.NewTypeSpec(TypeJSON),
schemahcl.NewTypeSpec(TypeJSONB),
schemahcl.NewTypeSpec(TypeUUID),
schemahcl.NewTypeSpec(TypeMoney),
schemahcl.NewTypeSpec(TypeTSVector),
schemahcl.NewTypeSpec(TypeTSQuery),
schemahcl.NewTypeSpec(TypeInt4Range),
schemahcl.NewTypeSpec(TypeInt4MultiRange),
schemahcl.NewTypeSpec(TypeInt8Range),
schemahcl.NewTypeSpec(TypeInt8MultiRange),
schemahcl.NewTypeSpec(TypeNumRange),
schemahcl.NewTypeSpec(TypeNumMultiRange),
schemahcl.NewTypeSpec(TypeTSRange),
schemahcl.NewTypeSpec(TypeTSMultiRange),
schemahcl.NewTypeSpec(TypeTSTZRange),
schemahcl.NewTypeSpec(TypeTSTZMultiRange),
schemahcl.NewTypeSpec(TypeDateRange),
schemahcl.NewTypeSpec(TypeDateMultiRange),
schemahcl.NewTypeSpec("hstore"),
schemahcl.NewTypeSpec("sql", schemahcl.WithAttributes(&schemahcl.TypeAttr{Name: "def", Required: true, Kind: reflect.String})),
),
// PostgreSQL internal and special types.
schemahcl.WithSpecs(func() (specs []*schemahcl.TypeSpec) {
for _, t := range []string{
typeOID, typeRegClass, typeRegCollation, typeRegConfig, typeRegDictionary, typeRegNamespace,
typeName, typeRegOper, typeRegOperator, typeRegProc, typeRegProcedure, typeRegRole, typeRegType,
} {
specs = append(specs, schemahcl.NewTypeSpec(t))
}
return specs
}()...),
schemahcl.WithSpecs(func() (specs []*schemahcl.TypeSpec) {
opts := []schemahcl.TypeSpecOption{
schemahcl.WithToSpec(func(t schema.Type) (*schemahcl.Type, error) {
i, ok := t.(*IntervalType)
if !ok {
return nil, fmt.Errorf("postgres: unexpected interval type %T", t)
}
spec := &schemahcl.Type{T: TypeInterval}
if i.F != "" {
spec.T = specutil.Var(strings.ToLower(i.F))
}
if p := i.Precision; p != nil && *p != defaultTimePrecision {
spec.Attrs = []*schemahcl.Attr{schemahcl.IntAttr("precision", *p)}
}
return spec, nil
}),
schemahcl.WithFromSpec(func(t *schemahcl.Type) (schema.Type, error) {
i := &IntervalType{T: TypeInterval}
if t.T != TypeInterval {
i.F = specutil.FromVar(t.T)
}
if a, ok := attr(t, "precision"); ok {
p, err := a.Int()
if err != nil {
return nil, fmt.Errorf(`postgres: parsing attribute "precision": %w`, err)
}
if p != defaultTimePrecision {
i.Precision = &p
}
}
return i, nil
}),
}
for _, f := range []string{"interval", "second", "day to second", "hour to second", "minute to second"} {
specs = append(specs, schemahcl.NewTypeSpec(specutil.Var(f), append(opts, schemahcl.WithAttributes(precisionTypeAttr()))...))
}
for _, f := range []string{"year", "month", "day", "hour", "minute", "year to month", "day to hour", "day to minute", "hour to minute"} {
specs = append(specs, schemahcl.NewTypeSpec(specutil.Var(f), opts...))
}
return specs
}()...),
)
func precisionTypeAttr() *schemahcl.TypeAttr {
return &schemahcl.TypeAttr{
Name: "precision",
Kind: reflect.Int,
Required: false,
}
}
func attr(typ *schemahcl.Type, key string) (*schemahcl.Attr, bool) {
for _, a := range typ.Attrs {
if a.K == key {
return a, true
}
}
return nil, false
}
func typeSpec(t schema.Type) (*schemahcl.Type, error) {
if t, ok := t.(*schema.TimeType); ok && t.T != TypeDate {
spec := &schemahcl.Type{T: timeAlias(t.T)}
if p := t.Precision; p != nil && *p != defaultTimePrecision {
spec.Attrs = []*schemahcl.Attr{schemahcl.IntAttr("precision", *p)}
}
return spec, nil
}
s, err := FormatType(t)
if err != nil {
return nil, err
}
return &schemahcl.Type{T: s}, nil
}
// formatTime overrides the default printing logic done by schemahcl.hclType.
func formatTime() schemahcl.TypeSpecOption {
return schemahcl.WithTypeFormatter(func(t *schemahcl.Type) (string, error) {
a, ok := attr(t, "precision")
if !ok {
return t.T, nil
}
p, err := a.Int()
if err != nil {
return "", fmt.Errorf(`postgres: parsing attribute "precision": %w`, err)
}
return FormatType(&schema.TimeType{T: t.T, Precision: &p})
})
}
// generatedType returns the default and only type for a generated column.
func generatedType(string) string { return "STORED" }