Skip to content

Commit b580f6f

Browse files
authored
Rewrite in Bash + jq (#5)
* Port Scala project to Bash + jq * Update CI to run Bash/jq tests * Restore full example in README.md * Add dependency and usage checks * Add input validation and better error messaging * Reorganize to packaged structure (bin/ directory) * Rename script to bigquery-schema-select to match project name * Add backtick quoting for BigQuery reserved keywords and update tests * Add unit test for reserved keyword quoting * Update README.md with motivation and quoted SQL example * Highlight avoidance of SELECT * and manual rewriting in Motivation * Refine README motivation: Public API analogy and more general medallion architecture description * Add bq tool check and update README prerequisites
1 parent e92e3e6 commit b580f6f

24 files changed

Lines changed: 295 additions & 412 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name: Scala CI
1+
name: CI
22

33
on:
44
push:
@@ -7,14 +7,9 @@ on:
77
branches: [ master ]
88

99
jobs:
10-
build:
10+
test:
1111
runs-on: ubuntu-latest
1212
steps:
1313
- uses: actions/checkout@v3
14-
- uses: actions/setup-java@v3
15-
with:
16-
distribution: 'temurin'
17-
java-version: '17'
18-
cache: 'sbt'
1914
- name: Run tests
20-
run: sbt test
15+
run: ./run-tests.sh

.scalafmt.conf

Lines changed: 0 additions & 2 deletions
This file was deleted.

README.md

Lines changed: 46 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,39 @@
11
# bigquery-schema-select
22

3-
![Scala CI](https://github.com/fpopic/bigquery-schema-select/workflows/Scala%20CI/badge.svg)
4-
[<img src="https://img.shields.io/maven-central/v/com.github.fpopic/bigquery-schema-select_2.13.svg?color=brightgreen&label=maven%20central%202.13"/>](https://search.maven.org/#search%7Cga%7C1%7Cbigquery-schema-select_2.13)
5-
63
Generates SQL query that selects all fields (recursively for nested fields) from the provided BigQuery schema file.
74

8-
### Installation
5+
### Motivation
96

10-
Download latest version `bigquery-schema-select_2.13-X.Y.jar` from [maven releases UI](https://repo1.maven.org/maven2/com/github/fpopic/bigquery-schema-select_2.13/) or using CLI:
7+
This tool is designed to help automate the creation of **explicit BigQuery views** that act as a strict schema "contract" between different layers of a medallion architecture. Think of these views as the **Public API** for your data: they provide a stable, documented interface that shields downstream consumers from the complexities and changes of the underlying raw data.
118

12-
```shell script
13-
# replace X.Y with the latest version
14-
wget -O ~/bigquery-schema-select_2.13-X.Y.jar https://repo1.maven.org/maven2/com/github/fpopic/bigquery-schema-select_2.13/X.Y/bigquery-schema-select_2.13-X.Y.jar
15-
```
9+
By generating an explicit `SELECT` statement that recursively expands `RECORD` and `REPEATED RECORD` types, it ensures that your views:
10+
- **Prevent Schema Drift**: New fields added to the underlying source table will not be exposed in the view until you explicitly update the schema and regenerate it (avoiding the pitfalls of `SELECT *`).
11+
- **Maintain Structure**: Uses `STRUCT(...)` and `ARRAY(SELECT AS STRUCT ...)` to fully specify the output record structure and maintain array order using `WITH OFFSET`.
12+
- **Enforce Naming Standards**: Optionally aliases camelCase fields to snake_case (using the `--use_snake_case` flag) to maintain a consistent naming convention across your data products.
13+
- **Automate Redundancy**: Avoids the error-prone and tedious process of manually rewriting complex nested SQL for dozens or hundreds of fields.
14+
15+
### Prerequisites
16+
17+
- `jq` installed on your system.
18+
- `bash` shell.
1619

1720
### Usage
1821

1922
Using existing table:
2023

2124
```shell script
22-
bq show --schema --format=prettyjson my_project:my_dataset.my_table | java -jar ~/bigquery-schema-select_2.13-X.Y.jar
25+
bq show --schema --format=prettyjson my_project:my_dataset.my_table | ./bin/bigquery-schema-select
2326
```
2427

2528
Using JSON schema file:
2629

2730
```shell script
28-
cat my_schema.json | java -jar ~/bigquery-schema-select_2.13-X.Y.jar
31+
cat my_schema.json | ./bin/bigquery-schema-select
2932
```
3033

34+
#### Example
35+
36+
Input `my_schema.json`:
3137
```json
3238
[
3339
{
@@ -116,49 +122,56 @@ cat my_schema.json | java -jar ~/bigquery-schema-select_2.13-X.Y.jar
116122
]
117123
```
118124

119-
Would generate:
125+
Generates:
120126
```sql
121127
SELECT
122-
A,
123-
B,
128+
`A`,
129+
`B`,
124130
STRUCT(
125131
STRUCT(
126-
C.D.E,
132+
`C`.`D`.`E`,
127133
ARRAY(
128134
SELECT AS STRUCT
129-
F.G
135+
`F`.`G`
130136
FROM
131-
UNNEST(C.D.F) AS F
137+
UNNEST(`C`.`D`.`F`) AS `F`
132138
WITH
133139
OFFSET
134140
ORDER BY
135141
OFFSET
136-
) AS F
137-
) AS D,
138-
C.H
139-
) AS C,
142+
) AS `F`
143+
) AS `D`,
144+
`C`.`H`
145+
) AS `C`,
140146
STRUCT(
141-
I.J,
142-
I.K
143-
) AS I,
147+
`I`.`J`,
148+
`I`.`K`
149+
) AS `I`,
144150
ARRAY(
145151
SELECT AS STRUCT
146-
L.M,
147-
L.N,
152+
`L`.`M`,
153+
`L`.`N`,
148154
STRUCT(
149-
L.O.P
150-
) AS O
155+
`L`.`O`.`P`
156+
) AS `O`
151157
FROM
152-
UNNEST(L) AS L
153-
WITH
158+
UNNEST(`L`) AS `L`
159+
WITH
154160
OFFSET
155161
ORDER BY
156162
OFFSET
157-
) AS L,
158-
Q
163+
) AS `L`,
164+
`Q`
159165
```
160166

161167
In case you would like to use snake_case for field names use flag `--use_snake_case`:
162168
```shell script
163-
cat my_schema.json | java -jar ~/bigquery-schema-select_2.13-X.Y.jar --use_snake_case
169+
cat my_schema.json | ./bin/bigquery-schema-select --use_snake_case
170+
```
171+
172+
### Development
173+
174+
Run tests:
175+
```shell script
176+
./run-tests.sh
164177
```

bin/bigquery-schema-select

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#!/bin/bash
2+
3+
# Ported from Scala to Bash + jq
4+
5+
# Check for dependencies
6+
if ! command -v jq >/dev/null 2>&1; then
7+
echo "Error: jq is not installed. Please install it (e.g., 'brew install jq' or 'sudo apt install jq')." >&2
8+
exit 1
9+
fi
10+
11+
if ! command -v bq >/dev/null 2>&1; then
12+
echo "Warning: bq (Google Cloud SDK) is not installed. You can still use this tool with JSON files, but you won't be able to fetch schemas directly from BigQuery." >&2
13+
fi
14+
15+
# Check for input (stdin)
16+
if [[ -t 0 ]]; then
17+
echo "Usage: cat schema.json | $0 [--use_snake_case]" >&2
18+
echo "Or: bq show --schema --format=prettyjson project:dataset.table | $0" >&2
19+
exit 1
20+
fi
21+
22+
# Read input once
23+
INPUT=$(cat)
24+
25+
# Validate JSON input
26+
if ! echo "$INPUT" | jq -e . >/dev/null 2>&1; then
27+
echo "Error: Input is not valid JSON." >&2
28+
if echo "$INPUT" | grep -iq "BigQuery error"; then
29+
echo "The input contains a BigQuery error. Please ensure your table reference follows the 'project:dataset.table' format (with a colon after the project ID)." >&2
30+
fi
31+
exit 1
32+
fi
33+
34+
USE_SNAKE_CASE=false
35+
if [[ "$1" == "--use_snake_case" ]]; then
36+
USE_SNAKE_CASE=true
37+
fi
38+
39+
echo "$INPUT" | jq -r --argjson useSnakeCase "$USE_SNAKE_CASE" '
40+
def quoteName(name): "`" + name + "`";
41+
42+
def calculateFieldName(name; useSnakeCase):
43+
if (useSnakeCase | not) then name
44+
else
45+
(name | split("") | .[0] |= ascii_downcase | .[0] as $first | .[1:] |
46+
reduce .[] as $char (""; . + (if ($char | test("[A-Z]")) then "_" + ($char | ascii_downcase) else $char end))
47+
| $first + .)
48+
end;
49+
50+
def toSelectClauseRecursive(current; depth; prefix; useSnakeCase):
51+
(if (prefix == null) then quoteName(current.name) else prefix + "." + quoteName(current.name) end) as $fullyQualifiedName |
52+
(" " * depth) as $indent |
53+
calculateFieldName(current.name; useSnakeCase) as $calculatedFieldName |
54+
quoteName($calculatedFieldName) as $quotedCalculatedFieldName |
55+
(if (useSnakeCase and $calculatedFieldName != current.name) then " AS " + $quotedCalculatedFieldName else "" end) as $alias |
56+
57+
if (current.type != "RECORD") then
58+
$indent + $fullyQualifiedName + $alias
59+
elif (current.type == "RECORD" and current.mode == "REPEATED") then
60+
quoteName(current.name) as $currentNameQuoted |
61+
($indent + "ARRAY(\n" +
62+
$indent + " SELECT AS STRUCT\n" +
63+
(current.fields | map(toSelectClauseRecursive(.; depth + 2; $currentNameQuoted; useSnakeCase)) | join(",\n")) + "\n" +
64+
$indent + " FROM\n" +
65+
$indent + " UNNEST(" + $fullyQualifiedName + ") AS " + $currentNameQuoted + "\n" +
66+
$indent + " WITH\n" +
67+
$indent + " OFFSET\n" +
68+
$indent + " ORDER BY\n" +
69+
$indent + " OFFSET\n" +
70+
$indent + ") AS " + $quotedCalculatedFieldName)
71+
else
72+
($indent + "STRUCT(\n" +
73+
(current.fields | map(toSelectClauseRecursive(.; depth + 1; $fullyQualifiedName; useSnakeCase)) | join(",\n")) + "\n" +
74+
$indent + ") AS " + $quotedCalculatedFieldName)
75+
end;
76+
77+
"SELECT\n" + (map(toSelectClauseRecursive(.; 1; null; $useSnakeCase)) | join(",\n"))
78+
'

build.sbt

Lines changed: 0 additions & 37 deletions
This file was deleted.

project/build.properties

Lines changed: 0 additions & 1 deletion
This file was deleted.

project/plugins.sbt

Lines changed: 0 additions & 3 deletions
This file was deleted.

publish.sbt

Lines changed: 0 additions & 37 deletions
This file was deleted.

run-tests.sh

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#!/bin/bash
2+
3+
# Test script for bq-schema-select.sh
4+
5+
set -e
6+
7+
echo "Running tests for bq-schema-select.sh..."
8+
9+
echo "Test 1: my_schema.json"
10+
./bin/bigquery-schema-select < test-resources/my_schema.json | diff - test-resources/my_select.sql
11+
echo "Test 1 passed!"
12+
13+
echo "Test 2: my_camel_schema.json --use_snake_case"
14+
./bin/bigquery-schema-select --use_snake_case < test-resources/my_camel_schema.json | diff - test-resources/my_camel_select.sql
15+
echo "Test 2 passed!"
16+
17+
echo "Test 3: my_camel_short_schema.json --use_snake_case"
18+
./bin/bigquery-schema-select --use_snake_case < test-resources/my_camel_short_schema.json | diff - test-resources/my_camel_short_select.sql
19+
echo "Test 3 passed!"
20+
21+
echo "Test 4: my_reserved_schema.json"
22+
./bin/bigquery-schema-select < test-resources/my_reserved_schema.json | diff - test-resources/my_reserved_select.sql
23+
echo "Test 4 passed!"
24+
25+
echo "All tests passed!"

src/main/scala/com/github/fpopic/bigqueryschemaselect/BigQuerySchemaField.scala

Lines changed: 0 additions & 36 deletions
This file was deleted.

0 commit comments

Comments
 (0)