sof-mssql 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +346 -0
  3. package/dist/cli.d.ts +7 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +85 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/fhirpath/transpiler.d.ts +18 -0
  8. package/dist/fhirpath/transpiler.d.ts.map +1 -0
  9. package/dist/fhirpath/transpiler.js +82 -0
  10. package/dist/fhirpath/transpiler.js.map +1 -0
  11. package/dist/fhirpath/visitor.d.ts +153 -0
  12. package/dist/fhirpath/visitor.d.ts.map +1 -0
  13. package/dist/fhirpath/visitor.js +1295 -0
  14. package/dist/fhirpath/visitor.js.map +1 -0
  15. package/dist/generated/grammar/fhirpathLexer.d.ts +88 -0
  16. package/dist/generated/grammar/fhirpathLexer.d.ts.map +1 -0
  17. package/dist/generated/grammar/fhirpathLexer.js +598 -0
  18. package/dist/generated/grammar/fhirpathLexer.js.map +1 -0
  19. package/dist/generated/grammar/fhirpathListener.d.ts +589 -0
  20. package/dist/generated/grammar/fhirpathListener.d.ts.map +1 -0
  21. package/dist/generated/grammar/fhirpathListener.js +4 -0
  22. package/dist/generated/grammar/fhirpathListener.js.map +1 -0
  23. package/dist/generated/grammar/fhirpathParser.d.ts +470 -0
  24. package/dist/generated/grammar/fhirpathParser.d.ts.map +1 -0
  25. package/dist/generated/grammar/fhirpathParser.js +3022 -0
  26. package/dist/generated/grammar/fhirpathParser.js.map +1 -0
  27. package/dist/generated/grammar/fhirpathVisitor.d.ts +372 -0
  28. package/dist/generated/grammar/fhirpathVisitor.d.ts.map +1 -0
  29. package/dist/generated/grammar/fhirpathVisitor.js +4 -0
  30. package/dist/generated/grammar/fhirpathVisitor.js.map +1 -0
  31. package/dist/index.d.ts +28 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +42 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/load.d.ts +14 -0
  36. package/dist/load.d.ts.map +1 -0
  37. package/dist/load.js +115 -0
  38. package/dist/load.js.map +1 -0
  39. package/dist/loader/connection.d.ts +36 -0
  40. package/dist/loader/connection.d.ts.map +1 -0
  41. package/dist/loader/connection.js +106 -0
  42. package/dist/loader/connection.js.map +1 -0
  43. package/dist/loader/discovery.d.ts +38 -0
  44. package/dist/loader/discovery.d.ts.map +1 -0
  45. package/dist/loader/discovery.js +107 -0
  46. package/dist/loader/discovery.js.map +1 -0
  47. package/dist/loader/index.d.ts +24 -0
  48. package/dist/loader/index.d.ts.map +1 -0
  49. package/dist/loader/index.js +193 -0
  50. package/dist/loader/index.js.map +1 -0
  51. package/dist/loader/progress.d.ts +70 -0
  52. package/dist/loader/progress.d.ts.map +1 -0
  53. package/dist/loader/progress.js +206 -0
  54. package/dist/loader/progress.js.map +1 -0
  55. package/dist/loader/stream.d.ts +21 -0
  56. package/dist/loader/stream.d.ts.map +1 -0
  57. package/dist/loader/stream.js +103 -0
  58. package/dist/loader/stream.js.map +1 -0
  59. package/dist/loader/tables.d.ts +43 -0
  60. package/dist/loader/tables.d.ts.map +1 -0
  61. package/dist/loader/tables.js +88 -0
  62. package/dist/loader/tables.js.map +1 -0
  63. package/dist/loader/types.d.ts +134 -0
  64. package/dist/loader/types.d.ts.map +1 -0
  65. package/dist/loader/types.js +8 -0
  66. package/dist/loader/types.js.map +1 -0
  67. package/dist/parser.d.ts +60 -0
  68. package/dist/parser.d.ts.map +1 -0
  69. package/dist/parser.js +226 -0
  70. package/dist/parser.js.map +1 -0
  71. package/dist/queryGenerator/ColumnExpressionGenerator.d.ts +52 -0
  72. package/dist/queryGenerator/ColumnExpressionGenerator.d.ts.map +1 -0
  73. package/dist/queryGenerator/ColumnExpressionGenerator.js +144 -0
  74. package/dist/queryGenerator/ColumnExpressionGenerator.js.map +1 -0
  75. package/dist/queryGenerator/ForEachProcessor.d.ts +127 -0
  76. package/dist/queryGenerator/ForEachProcessor.d.ts.map +1 -0
  77. package/dist/queryGenerator/ForEachProcessor.js +351 -0
  78. package/dist/queryGenerator/ForEachProcessor.js.map +1 -0
  79. package/dist/queryGenerator/PathParser.d.ts +64 -0
  80. package/dist/queryGenerator/PathParser.d.ts.map +1 -0
  81. package/dist/queryGenerator/PathParser.js +164 -0
  82. package/dist/queryGenerator/PathParser.js.map +1 -0
  83. package/dist/queryGenerator/SelectClauseBuilder.d.ts +63 -0
  84. package/dist/queryGenerator/SelectClauseBuilder.d.ts.map +1 -0
  85. package/dist/queryGenerator/SelectClauseBuilder.js +196 -0
  86. package/dist/queryGenerator/SelectClauseBuilder.js.map +1 -0
  87. package/dist/queryGenerator/SelectCombinationExpander.d.ts +42 -0
  88. package/dist/queryGenerator/SelectCombinationExpander.d.ts.map +1 -0
  89. package/dist/queryGenerator/SelectCombinationExpander.js +95 -0
  90. package/dist/queryGenerator/SelectCombinationExpander.js.map +1 -0
  91. package/dist/queryGenerator/WhereClauseBuilder.d.ts +20 -0
  92. package/dist/queryGenerator/WhereClauseBuilder.d.ts.map +1 -0
  93. package/dist/queryGenerator/WhereClauseBuilder.js +63 -0
  94. package/dist/queryGenerator/WhereClauseBuilder.js.map +1 -0
  95. package/dist/queryGenerator/index.d.ts +10 -0
  96. package/dist/queryGenerator/index.d.ts.map +1 -0
  97. package/dist/queryGenerator/index.js +19 -0
  98. package/dist/queryGenerator/index.js.map +1 -0
  99. package/dist/queryGenerator.d.ts +61 -0
  100. package/dist/queryGenerator.d.ts.map +1 -0
  101. package/dist/queryGenerator.js +187 -0
  102. package/dist/queryGenerator.js.map +1 -0
  103. package/dist/tests/sqlOnFhir.test.d.ts +11 -0
  104. package/dist/tests/sqlOnFhir.test.d.ts.map +1 -0
  105. package/dist/tests/sqlOnFhir.test.js +24 -0
  106. package/dist/tests/sqlOnFhir.test.js.map +1 -0
  107. package/dist/tests/utils/database.d.ts +38 -0
  108. package/dist/tests/utils/database.d.ts.map +1 -0
  109. package/dist/tests/utils/database.js +258 -0
  110. package/dist/tests/utils/database.js.map +1 -0
  111. package/dist/tests/utils/generator.d.ts +58 -0
  112. package/dist/tests/utils/generator.d.ts.map +1 -0
  113. package/dist/tests/utils/generator.js +195 -0
  114. package/dist/tests/utils/generator.js.map +1 -0
  115. package/dist/tests/utils/reporter.d.ts +83 -0
  116. package/dist/tests/utils/reporter.d.ts.map +1 -0
  117. package/dist/tests/utils/reporter.js +245 -0
  118. package/dist/tests/utils/reporter.js.map +1 -0
  119. package/dist/tests/utils/sqlOnFhir.d.ts +33 -0
  120. package/dist/tests/utils/sqlOnFhir.d.ts.map +1 -0
  121. package/dist/tests/utils/sqlOnFhir.js +281 -0
  122. package/dist/tests/utils/sqlOnFhir.js.map +1 -0
  123. package/dist/tests/utils/testContext.d.ts +18 -0
  124. package/dist/tests/utils/testContext.d.ts.map +1 -0
  125. package/dist/tests/utils/testContext.js +25 -0
  126. package/dist/tests/utils/testContext.js.map +1 -0
  127. package/dist/tests/utils/types.d.ts +31 -0
  128. package/dist/tests/utils/types.d.ts.map +1 -0
  129. package/dist/tests/utils/types.js +9 -0
  130. package/dist/tests/utils/types.js.map +1 -0
  131. package/dist/types.d.ts +288 -0
  132. package/dist/types.d.ts.map +1 -0
  133. package/dist/types.js +6 -0
  134. package/dist/types.js.map +1 -0
  135. package/package.json +76 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,346 @@
1
+ # SQL on FHIR views for Microsoft SQL Server
2
+
3
+ A TypeScript library and CLI tool for loading FHIR into Microsoft SQL Server,
4
+ and transpiling [SQL on FHIR](https://sql-on-fhir.org/) view definitions into
5
+ T-SQL queries.
6
+
7
+ ## Features
8
+
9
+ - **SQL on FHIR v2 compliance** - Implements
10
+ the [SQL on FHIR v2 specification](https://sql-on-fhir.org/ig/2.0.0/) for
11
+ transforming FHIR resources into tabular views
12
+ - **FHIRPath support** - Full support for FHIRPath expressions in column
13
+ definitions and filters
14
+ - **T-SQL optimisation** - Generates efficient T-SQL queries using `JSON_VALUE`,
15
+ `JSON_QUERY`, and `OPENJSON`
16
+ - **forEach support** - Handles array flattening with `CROSS APPLY` for nested
17
+ FHIR resources
18
+ - **Union support** - Supports `unionAll` for polymorphic fields
19
+ - **Type casting** - Automatic SQL type inference and casting based on FHIR data
20
+ types
21
+ - **WHERE clauses** - Supports view-level filtering with FHIRPath expressions
22
+ - **Bulk NDJSON loader** - Built-in loader for importing FHIR resources from
23
+ NDJSON files
24
+
25
+ ## Quick start
26
+
27
+ The easiest way to use sof-mssql is via `npx`:
28
+
29
+ ```bash
30
+ # Load FHIR resources from NDJSON files
31
+ npx sof-mssql load ./data --host localhost --user sa --password pass --database fhir
32
+
33
+ # Transpile a ViewDefinition from stdin to stdout
34
+ npx sof-mssql transpile <some.ViewDefinition.json >output.sql
35
+
36
+ # Or use file arguments
37
+ npx sof-mssql transpile --input some.ViewDefinition.json --output output.sql
38
+ ```
39
+
40
+ ## Installation
41
+
42
+ For programmatic use, install via npm:
43
+
44
+ ```bash
45
+ npm install sof-mssql
46
+ ```
47
+
48
+ ## CLI usage
49
+
50
+ The CLI provides two main commands: `load` for bulk loading NDJSON files into
51
+ SQL Server, and `transpile` for converting ViewDefinitions to T-SQL.
52
+
53
+ ### Loading NDJSON files
54
+
55
+ Bulk load FHIR resources from NDJSON files into SQL Server:
56
+
57
+ ```bash
58
+ # Load all NDJSON files from a directory
59
+ npx sof-mssql load ./data \
60
+ --host localhost \
61
+ --user sa \
62
+ --password yourpassword \
63
+ --database fhir
64
+
65
+ # Load with environment variables
66
+ export MSSQL_HOST=localhost MSSQL_USER=sa MSSQL_PASSWORD=pass MSSQL_DATABASE=fhir
67
+ npx sof-mssql load ./data
68
+
69
+ # Load with custom table and batch settings
70
+ npx sof-mssql load ./data \
71
+ --table-name my_resources \
72
+ --batch-size 5000 \
73
+ --parallel 2
74
+
75
+ # Preview what would be loaded
76
+ npx sof-mssql load ./data --dry-run
77
+ ```
78
+
79
+ **File naming:** Files must follow the pattern `{ResourceType}.ndjson` (e.g.,
80
+ `Patient.ndjson`, `Observation.ndjson`). The resource type is extracted from the
81
+ filename and stored in the `resource_type` column.
82
+
83
+ **Database options:**
84
+
85
+ - `--host <host>` - Database server hostname
86
+ - `--port <port>` - Database server port (default: 1433)
87
+ - `--user <user>` - Database username
88
+ - `--password <password>` - Database password
89
+ - `--database <database>` - Database name
90
+ - `--trust-server-certificate` - Trust server certificate
91
+
92
+ **Loading options:**
93
+
94
+ - `--table-name <name>` - Table name (default: `fhir_resources`)
95
+ - `--schema-name <name>` - Schema name (default: `dbo`)
96
+ - `--resource-type <type>` - Load only specific resource type
97
+ - `--truncate` - Truncate table before loading
98
+ - `--no-create-table` - Don't create table if it doesn't exist
99
+
100
+ **Performance options:**
101
+
102
+ - `--batch-size <size>` - Rows per batch (default: 1000)
103
+ - `--parallel <count>` - Parallel file processing (default: 4, use 1-2 for best
104
+ reliability)
105
+
106
+ **Output options:**
107
+
108
+ - `--dry-run` - Preview without loading
109
+ - `--verbose` - Show detailed progress
110
+ - `--progress` - Show progress bar
111
+ - `--quiet` - Minimal output
112
+ - `--continue-on-error` - Continue if a file fails
113
+
114
+ ### Transpiling ViewDefinitions
115
+
116
+ Convert SQL on FHIR ViewDefinitions to T-SQL:
117
+
118
+ ```bash
119
+ # Read from stdin, write to stdout
120
+ npx sof-mssql transpile <some.ViewDefinition.json
121
+
122
+ # Read from file, write to stdout
123
+ npx sof-mssql transpile --input some.ViewDefinition.json
124
+
125
+ # Read from stdin, write to file
126
+ npx sof-mssql transpile <some.ViewDefinition.json --output query.sql
127
+
128
+ # Read from file, write to file
129
+ npx sof-mssql transpile --input some.ViewDefinition.json --output query.sql
130
+
131
+ # Fetch from remote server and transpile
132
+ curl https://example.com/fhir/ViewDefinition/1 | npx sof-mssql transpile
133
+ ```
134
+
135
+ **Options:**
136
+
137
+ - `-i, --input <file>` - Input ViewDefinition JSON file (default: stdin)
138
+ - `-o, --output <file>` - Output SQL file (default: stdout)
139
+
140
+ **Global options:**
141
+
142
+ - `-V, --version` - Output the version number
143
+ - `-h, --help` - Display help information
144
+
145
+ ### Using transpiled SQL
146
+
147
+ Once you've transpiled a ViewDefinition to T-SQL, you can use it to create
148
+ database views or tables.
149
+
150
+ #### Creating a view
151
+
152
+ Views provide a virtual table based on the query, recomputed each time the view
153
+ is queried:
154
+
155
+ ```bash
156
+ # Transpile ViewDefinition to SQL file
157
+ npx sof-mssql transpile --input patient_demographics.json --output patient_demographics.sql
158
+
159
+ # Connect to SQL Server and create the view
160
+ sqlcmd -S localhost -U sa -P yourpassword -d fhir -Q "
161
+ CREATE VIEW [dbo].[patient_demographics] AS
162
+ $(cat patient_demographics.sql)
163
+ "
164
+ ```
165
+
166
+ Or directly in SQL Server Management Studio:
167
+
168
+ ```sql
169
+ CREATE VIEW [dbo].[patient_demographics] AS
170
+ SELECT r.id AS [id],
171
+ JSON_VALUE(r.json, '$.name[0].family') AS [family_name],
172
+ CAST(JSON_VALUE(r.json, '$.birthDate') AS DATETIME2) AS [birth_date]
173
+ FROM [dbo].[fhir_resources] AS [r]
174
+ WHERE [r].[resource_type] = 'Patient'
175
+ ```
176
+
177
+ #### Creating a materialised table
178
+
179
+ For better query performance, you can materialise the view results into a
180
+ physical table:
181
+
182
+ ```sql
183
+ -- Create and populate the table in one statement
184
+ SELECT *
185
+ INTO [dbo].[patient_demographics]
186
+ FROM (
187
+ SELECT
188
+ r.id AS [id], JSON_VALUE(r.json, '$.name[0].family') AS [family_name], CAST (JSON_VALUE(r.json, '$.birthDate') AS DATETIME2) AS [birth_date]
189
+ FROM [dbo].[fhir_resources] AS [r]
190
+ WHERE [r].[resource_type] = 'Patient'
191
+ ) AS view_results
192
+ ```
193
+
194
+ To refresh a materialised table after data changes:
195
+
196
+ ```sql
197
+ -- Truncate and reload
198
+ TRUNCATE TABLE [dbo].[patient_demographics];
199
+
200
+ INSERT INTO [dbo].[patient_demographics]
201
+ SELECT r.id AS [id],
202
+ JSON_VALUE(r.json, '$.name[0].family') AS [family_name],
203
+ CAST(JSON_VALUE(r.json, '$.birthDate') AS DATETIME2) AS [birth_date]
204
+ FROM [dbo].[fhir_resources] AS [r]
205
+ WHERE [r].[resource_type] = 'Patient'
206
+ ```
207
+
208
+ ## Programmatic usage
209
+
210
+ ### Basic usage
211
+
212
+ ```javascript
213
+ import {SqlOnFhir} from 'sof-mssql';
214
+
215
+ // Create an instance with default configuration
216
+ const sqlOnFhir = new SqlOnFhir();
217
+
218
+ // Transpile a ViewDefinition to T-SQL
219
+ const viewDefinition = {
220
+ resourceType: 'ViewDefinition',
221
+ resource: 'Patient',
222
+ name: 'patient_demographics',
223
+ select: [
224
+ {
225
+ column: [
226
+ {
227
+ name: 'id',
228
+ path: 'id',
229
+ type: 'id'
230
+ },
231
+ {
232
+ name: 'family_name',
233
+ path: 'name.family',
234
+ type: 'string'
235
+ },
236
+ {
237
+ name: 'birth_date',
238
+ path: 'birthDate',
239
+ type: 'date'
240
+ }
241
+ ]
242
+ }
243
+ ]
244
+ };
245
+
246
+ const result = sqlOnFhir.transpile(viewDefinition);
247
+
248
+ console.log(result.sql);
249
+ // Output:
250
+ // SELECT
251
+ // r.id AS [id],
252
+ // JSON_VALUE(r.json, '$.name[0].family') AS [family_name],
253
+ // CAST(JSON_VALUE(r.json, '$.birthDate') AS DATETIME2) AS [birth_date]
254
+ // FROM [dbo].[fhir_resources] AS [r]
255
+ // WHERE [r].[resource_type] = 'Patient'
256
+
257
+ // Access column metadata
258
+ console.log(result.columns);
259
+ // Output:
260
+ // [
261
+ // { name: 'id', type: 'NVARCHAR(64)', nullable: true },
262
+ // { name: 'family_name', type: 'NVARCHAR(MAX)', nullable: true },
263
+ // { name: 'birth_date', type: 'DATETIME2', nullable: true }
264
+ // ]
265
+ ```
266
+
267
+ ### Custom table configuration
268
+
269
+ ```javascript
270
+ const sqlOnFhir = new SqlOnFhir({
271
+ tableName: 'my_fhir_data',
272
+ schemaName: 'clinical',
273
+ resourceIdColumn: 'resource_id',
274
+ resourceJsonColumn: 'resource_data'
275
+ });
276
+ ```
277
+
278
+ ### Working with ViewDefinition strings
279
+
280
+ ```javascript
281
+ import {SqlOnFhir} from 'sof-mssql';
282
+
283
+ const sqlOnFhir = new SqlOnFhir();
284
+
285
+ // From JSON string
286
+ const viewDefJson = JSON.stringify(viewDefinition);
287
+ const result = sqlOnFhir.transpile(viewDefJson);
288
+
289
+ // From FHIR resource (with resourceType)
290
+ const fhirResource = {
291
+ resourceType: 'ViewDefinition',
292
+ // ... rest of ViewDefinition
293
+ };
294
+ const result2 = sqlOnFhir.transpile(fhirResource);
295
+ ```
296
+
297
+ ## Database setup
298
+
299
+ ### Table structure
300
+
301
+ sof-mssql expects FHIR resources to be stored in a table with the following
302
+ structure:
303
+
304
+ ```sql
305
+ CREATE TABLE [dbo].[fhir_resources] (
306
+ [id] INT IDENTITY (1, 1) NOT NULL PRIMARY KEY,
307
+ [resource_type] NVARCHAR (64) NOT NULL,
308
+ [json] NVARCHAR (MAX) NOT NULL
309
+ );
310
+
311
+ -- Create an index on resource_type for efficient filtering by resource type
312
+ CREATE INDEX [IX_fhir_resources_resource_type]
313
+ ON [dbo].[fhir_resources] ([resource_type]);
314
+ ```
315
+
316
+ The generated queries use:
317
+
318
+ - `resource_type` column for filtering by FHIR resource type (indexed for
319
+ performance)
320
+ - `json` column containing the complete FHIR resource as JSON
321
+ - SQL Server's JSON functions (`JSON_VALUE`, `JSON_QUERY`, `OPENJSON`) for data
322
+ extraction
323
+
324
+ **Performance recommendation:** The index on `resource_type` is strongly
325
+ recommended as every ViewDefinition query filters by resource type. Without this
326
+ index, queries will perform full table scans.
327
+
328
+ ### Loading data
329
+
330
+ The easiest way to populate your database is using the built-in NDJSON loader (
331
+ see [Loading NDJSON files](#loading-ndjson-files) above), which automatically
332
+ creates the table with the correct structure. All FHIR resources are stored in a
333
+ single table (default: `fhir_resources`), with the resource type extracted from
334
+ the filename.
335
+
336
+ ## Contributing
337
+
338
+ Contributions are welcome! Please read our [CONTRIBUTING](CONTRIBUTING.md)
339
+ and [CODE_OF_CONDUCT](CODE_OF_CONDUCT.md) documents for guidelines on how to
340
+ get involved.
341
+
342
+ ## License
343
+
344
+ Copyright © 2025, Commonwealth Scientific and Industrial Research Organisation
345
+ (CSIRO) ABN 41 687 119 230. Licensed under
346
+ the [Apache License, version 2.0](https://www.apache.org/licenses/LICENSE-2.0).
package/dist/cli.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI for SQL on FHIR tooling.
4
+ * Supports transpiling ViewDefinitions and loading NDJSON data.
5
+ */
6
+ export {};
7
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA;;;GAGG"}
package/dist/cli.js ADDED
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * CLI for SQL on FHIR tooling.
5
+ * Supports transpiling ViewDefinitions and loading NDJSON data.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ const commander_1 = require("commander");
9
+ const fs_1 = require("fs");
10
+ const index_js_1 = require("./index.js");
11
+ const load_js_1 = require("./load.js");
12
+ /**
13
+ * Read input from stdin or file.
14
+ */
15
+ async function readInput(inputFile) {
16
+ if (inputFile) {
17
+ return (0, fs_1.readFileSync)(inputFile, "utf-8");
18
+ }
19
+ // Read from stdin.
20
+ const chunks = [];
21
+ for await (const chunk of process.stdin) {
22
+ chunks.push(chunk);
23
+ }
24
+ return Buffer.concat(chunks).toString("utf-8");
25
+ }
26
+ /**
27
+ * Write output to stdout or file.
28
+ */
29
+ function writeOutput(sql, outputFile) {
30
+ if (outputFile) {
31
+ (0, fs_1.writeFileSync)(outputFile, sql, "utf-8");
32
+ }
33
+ else {
34
+ process.stdout.write(sql);
35
+ }
36
+ }
37
+ /**
38
+ * Create the transpile command (default behaviour).
39
+ */
40
+ function createTranspileCommand() {
41
+ const command = new commander_1.Command("transpile");
42
+ command
43
+ .description("Transpile SQL on FHIR ViewDefinitions to T-SQL queries")
44
+ .option("-i, --input <file>", "Input ViewDefinition JSON file (default: stdin)")
45
+ .option("-o, --output <file>", "Output SQL file (default: stdout)")
46
+ .action(async (options) => {
47
+ try {
48
+ // Read ViewDefinition from stdin or file.
49
+ const input = await readInput(options.input);
50
+ // Parse and validate JSON.
51
+ const viewDefinition = JSON.parse(input);
52
+ // Transpile to SQL.
53
+ const sqlOnFhir = new index_js_1.SqlOnFhir();
54
+ const result = sqlOnFhir.transpile(viewDefinition);
55
+ // Write SQL to stdout or file.
56
+ writeOutput(result.sql, options.output);
57
+ }
58
+ catch (err) {
59
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
60
+ process.exit(1);
61
+ }
62
+ });
63
+ return command;
64
+ }
65
+ /**
66
+ * Main CLI entry point.
67
+ */
68
+ async function main() {
69
+ const program = new commander_1.Command();
70
+ program
71
+ .name("sof-mssql")
72
+ .description("SQL on FHIR tooling for MS SQL Server")
73
+ .version("1.0.0");
74
+ // Add subcommands.
75
+ program.addCommand(createTranspileCommand());
76
+ program.addCommand((0, load_js_1.createLoadCommand)());
77
+ // Parse arguments.
78
+ await program.parseAsync(process.argv);
79
+ // If no command specified, show help.
80
+ if (process.argv.length <= 2) {
81
+ program.help();
82
+ }
83
+ }
84
+ void main();
85
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;AAEA;;;GAGG;;AAEH,yCAAoC;AACpC,2BAAiD;AACjD,yCAAuC;AACvC,uCAA8C;AAE9C;;GAEG;AACH,KAAK,UAAU,SAAS,CAAC,SAAkB;IACzC,IAAI,SAAS,EAAE,CAAC;QACd,OAAO,IAAA,iBAAY,EAAC,SAAS,EAAE,OAAO,CAAC,CAAC;IAC1C,CAAC;IAED,mBAAmB;IACnB,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;QACxC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AACjD,CAAC;AAED;;GAEG;AACH,SAAS,WAAW,CAAC,GAAW,EAAE,UAAmB;IACnD,IAAI,UAAU,EAAE,CAAC;QACf,IAAA,kBAAa,EAAC,UAAU,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;IAC1C,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC5B,CAAC;AACH,CAAC;AAED;;GAEG;AACH,SAAS,sBAAsB;IAC7B,MAAM,OAAO,GAAG,IAAI,mBAAO,CAAC,WAAW,CAAC,CAAC;IAEzC,OAAO;SACJ,WAAW,CAAC,wDAAwD,CAAC;SACrE,MAAM,CACL,oBAAoB,EACpB,iDAAiD,CAClD;SACA,MAAM,CAAC,qBAAqB,EAAE,mCAAmC,CAAC;SAClE,MAAM,CAAC,KAAK,EAAE,OAA4C,EAAE,EAAE;QAC7D,IAAI,CAAC;YACH,0CAA0C;YAC1C,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAE7C,2BAA2B;YAC3B,MAAM,cAAc,GAAW,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAEjD,oBAAoB;YACpB,MAAM,SAAS,GAAG,IAAI,oBAAS,EAAE,CAAC;YAClC,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,cAAc,CAAC,CAAC;YAEnD,+BAA+B;YAC/B,WAAW,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;QAC1C,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CACX,UAAU,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAC7D,CAAC;YACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC;IACH,CAAC,CAAC,CAAC;IAEL,OAAO,OAAO,CAAC;AACjB,CAAC;AACD;;GAEG;AACH,KAAK,UAAU,IAAI;IACjB,MAAM,OAAO,GAAG,IAAI,mBAAO,EAAE,CAAC;IAE9B,OAAO;SACJ,IAAI,CAAC,WAAW,CAAC;SACjB,WAAW,CAAC,uCAAuC,CAAC;SACpD,OAAO,CAAC,OAAO,CAAC,CAAC;IAEpB,mBAAmB;IACnB,OAAO,CAAC,UAAU,CAAC,sBAAsB,EAAE,CAAC,CAAC;IAC7C,OAAO,CAAC,UAAU,CAAC,IAAA,2BAAiB,GAAE,CAAC,CAAC;IAExC,mBAAmB;IACnB,MAAM,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvC,sCAAsC;IACtC,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;QAC7B,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;AACH,CAAC;AAED,KAAK,IAAI,EAAE,CAAC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * FHIRPath expression transpiler to T-SQL.
3
+ * Converts FHIRPath expressions to equivalent T-SQL expressions for MS SQL Server.
4
+ */
5
+ import { TranspilerContext } from "./visitor";
6
+ export { TranspilerContext } from "./visitor";
7
+ export declare class Transpiler {
8
+ /**
9
+ * Transpile a FHIRPath expression to T-SQL.
10
+ */
11
+ static transpile(expression: string, context: TranspilerContext): string;
12
+ private static parseExpression;
13
+ /**
14
+ * Get the SQL data type for a FHIRPath expression result.
15
+ */
16
+ static inferSqlType(fhirType?: string): string;
17
+ }
18
+ //# sourceMappingURL=transpiler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transpiler.d.ts","sourceRoot":"","sources":["../../src/fhirpath/transpiler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAQH,OAAO,EAAyB,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAGrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAE9C,qBAAa,UAAU;IACrB;;OAEG;IACH,MAAM,CAAC,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,GAAG,MAAM;IAkBxE,OAAO,CAAC,MAAM,CAAC,eAAe;IA4B9B;;OAEG;IACH,MAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM;CA8B/C"}