Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow DROP VIEW and DROP MATERIALIZED VIEW #21

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions _examples/python/table_and_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""
This example creates a dataset, table, and view,
shows that the output of the table and view are expected,
and removes the dataset, table, and view.
"""
Comment on lines +1 to +5

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😍 incredible!!


from google.api_core.client_options import ClientOptions
from google.auth.credentials import AnonymousCredentials
from google.cloud import bigquery

if __name__ == "__main__":
client_options = ClientOptions(api_endpoint="http://0.0.0.0:9050")
client = bigquery.Client(
"test",
client_options=client_options,
credentials=AnonymousCredentials(),
)

client.create_dataset("example_dataset")

print("Setting up table")
example_table = client.create_table(
bigquery.Table(
"test.example_dataset.example_table",
[
bigquery.SchemaField("string_field", "STRING"),
],
)
)
print("Loading table")
rows_to_insert = [
{"string_field": "An example string"},
{"string_field": "Hello, BigQuery!"},
]
_ = client.insert_rows_json("test.example_dataset.example_table", rows_to_insert)

print("Setting up view")
_view_definition = bigquery.Table("test.example_dataset.example_view")
_view_definition.view_query = "SELECT * FROM `test.example_dataset.example_table`"
example_view = client.create_table(_view_definition)

print("Running queries")
table_data = list(
client.query(
query="SELECT * FROM example_dataset.example_table",
job_config=bigquery.QueryJobConfig(),
)
)

view_data = list(
client.query(
query="SELECT * FROM example_dataset.example_view",
job_config=bigquery.QueryJobConfig(),
)
)

assert table_data == view_data

print("Cleaning up tables")
client.delete_table(example_view)
client.delete_table(example_table)
client.delete_dataset("example_dataset")
21 changes: 17 additions & 4 deletions internal/contentdata/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

"github.com/goccy/bigquery-emulator/internal/connection"
"github.com/goccy/bigquery-emulator/internal/logger"
"github.com/goccy/bigquery-emulator/internal/metadata"
internaltypes "github.com/goccy/bigquery-emulator/internal/types"
"github.com/goccy/bigquery-emulator/types"
)
Expand Down Expand Up @@ -428,7 +429,7 @@ func (r *Repository) AddTableData(ctx context.Context, tx *connection.Tx, projec
return nil
}

func (r *Repository) DeleteTables(ctx context.Context, tx *connection.Tx, projectID, datasetID string, tableIDs []string) error {
func (r *Repository) DeleteTables(ctx context.Context, tx *connection.Tx, projectID, datasetID string, tables []*metadata.Table) error {
tx.SetProjectAndDataset(projectID, datasetID)
if err := tx.ContentRepoMode(); err != nil {
return err
Expand All @@ -437,10 +438,22 @@ func (r *Repository) DeleteTables(ctx context.Context, tx *connection.Tx, projec
_ = tx.MetadataRepoMode()
}()

for _, tableID := range tableIDs {
tablePath := r.tablePath(projectID, datasetID, tableID)
for _, table := range tables {
tablePath := r.tablePath(projectID, datasetID, table.ID)
logger.Logger(ctx).Debug("delete table", zap.String("table", tablePath))
query := fmt.Sprintf("DROP TABLE `%s`", tablePath)
tableContent, err := table.Content()
if err != nil {
return fmt.Errorf("failed to delete table %s: %w", tablePath, err)
}
var query string
switch tableContent.Type {
case string(internaltypes.MaterializedViewTableType):
query = fmt.Sprintf("DROP MATERIALIZED VIEW `%s`", tablePath)
case string(internaltypes.DefaultTableType), string(internaltypes.ViewTableType):
query = fmt.Sprintf("DROP %s `%s`", tableContent.Type, tablePath)
default:
return fmt.Errorf("failed to delete table with unsupported table type: %s", tableContent.Type)
}
if _, err := tx.Tx().ExecContext(ctx, query); err != nil {
return fmt.Errorf("failed to delete table %s: %w", query, err)
}
Expand Down
10 changes: 10 additions & 0 deletions internal/types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ import (
bigqueryv2 "google.golang.org/api/bigquery/v2"
)

type TableType string

const (
DefaultTableType TableType = "TABLE"
ViewTableType TableType = "VIEW"
ExternalTableType TableType = "EXTERNAL"
MaterializedViewTableType TableType = "MATERIALIZED_VIEW"
SnapshotTableType TableType = "SNAPSHOT"
)

type (
GetQueryResultsResponse struct {
JobReference *bigqueryv2.JobReference `json:"jobReference"`
Expand Down
18 changes: 4 additions & 14 deletions server/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ func (h *datasetsDeleteHandler) Handle(ctx context.Context, r *datasetsDeleteReq
}
}

if err := r.server.contentRepo.DeleteTables(ctx, tx, r.project.ID, r.dataset.ID, tableIDs); err != nil {
if err := r.server.contentRepo.DeleteTables(ctx, tx, r.project.ID, r.dataset.ID, tables); err != nil {
return fmt.Errorf("failed to delete tables: %w", err)
}
}
Expand Down Expand Up @@ -2528,7 +2528,7 @@ func (h *tablesDeleteHandler) Handle(ctx context.Context, r *tablesDeleteRequest
tx,
r.project.ID,
r.dataset.ID,
[]string{r.table.ID},
[]*metadata.Table{r.table},
); err != nil {
return fmt.Errorf("failed to delete table %s: %w", r.table.ID, err)
}
Expand Down Expand Up @@ -2632,24 +2632,14 @@ type tablesInsertRequest struct {
table *bigqueryv2.Table
}

type TableType string

const (
DefaultTableType TableType = "TABLE"
ViewTableType TableType = "VIEW"
ExternalTableType TableType = "EXTERNAL"
MaterializedViewTableType TableType = "MATERIALIZED_VIEW"
SnapshotTableType TableType = "SNAPSHOT"
)

func createTableMetadata(ctx context.Context, tx *connection.Tx, server *Server, project *metadata.Project, dataset *metadata.Dataset, table *bigqueryv2.Table) (*bigqueryv2.Table, *ServerError) {
now := time.Now().Unix()
table.Id = fmt.Sprintf("%s:%s.%s", project.ID, dataset.ID, table.TableReference.TableId)
table.CreationTime = now
table.LastModifiedTime = uint64(now)
table.Type = string(DefaultTableType) // TODO: need to handle other table types
table.Type = string(internaltypes.DefaultTableType) // TODO: need to handle other table types
if table.View != nil {
table.Type = string(ViewTableType)
table.Type = string(internaltypes.ViewTableType)
}
table.Kind = "bigquery#table"
table.SelfLink = fmt.Sprintf(
Expand Down
Loading