Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore: migrate data source to v1 store (#4358)

Danny Xud313ec5f8202
diff --git a/api/data_source.go b/api/data_source.go
index ef784c861d..26e999c7a3 100644
--- a/api/data_source.go
+++ b/api/data_source.go
@@ -8,8 +8,6 @@ import (
const (
// AdminDataSourceName is the name for administrative data source.
AdminDataSourceName = "Admin data source"
- // ReadWriteDataSourceName is the name for read/write data source.
- ReadWriteDataSourceName = "Read/Write data source"
// ReadOnlyDataSourceName is the name for read-only data source.
ReadOnlyDataSourceName = "ReadOnly data source"
// UnknownDataSourceName is the name for unknown data source.
@@ -23,8 +21,6 @@ func DataSourceNameFromType(dataSourceType DataSourceType) string {
return AdminDataSourceName
case RO:
return ReadOnlyDataSourceName
- case RW:
- return ReadWriteDataSourceName
}
return UnknownDataSourceName
}
@@ -35,8 +31,6 @@ type DataSourceType string
const (
// Admin is the ADMIN type of data source.
Admin DataSourceType = "ADMIN"
- // RW is the read/write type of data source.
- RW DataSourceType = "RW"
// RO is the read-only type of data source.
RO DataSourceType = "RO"
)
@@ -80,14 +74,9 @@ type DataSource struct {
DatabaseID int `jsonapi:"attr,databaseId"`
// Domain specific fields
- Name string `jsonapi:"attr,name"`
- Type DataSourceType `jsonapi:"attr,type"`
- Username string `jsonapi:"attr,username"`
- // Do not return the password to client
- Password string
- SslCa string
- SslCert string
- SslKey string
+ Name string `jsonapi:"attr,name"`
+ Type DataSourceType `jsonapi:"attr,type"`
+ Username string `jsonapi:"attr,username"`
Host string `jsonapi:"attr,host"`
Port string `jsonapi:"attr,port"`
Options DataSourceOptions `jsonapi:"attr,options"`
@@ -96,15 +85,6 @@ type DataSource struct {
// DataSourceCreate is the API message for creating a data source.
type DataSourceCreate struct {
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- CreatorID int
-
- // Related fields
- InstanceID int `jsonapi:"attr,instanceId"`
- DatabaseID int `jsonapi:"attr,databaseId"`
-
- // Domain specific fields
Name string `jsonapi:"attr,name"`
Type DataSourceType `jsonapi:"attr,type"`
Username string `jsonapi:"attr,username"`
@@ -118,35 +98,8 @@ type DataSourceCreate struct {
Database string `jsonapi:"attr,database"`
}
-// DataSourceFind is the API message for finding data sources.
-type DataSourceFind struct {
- ID *int
-
- // Related fields
- InstanceID *int
- DatabaseID *int
-
- // Domain specific fields
- Type *DataSourceType
-}
-
-func (find *DataSourceFind) String() string {
- str, err := json.Marshal(*find)
- if err != nil {
- return err.Error()
- }
- return string(str)
-}
-
// DataSourcePatch is the API message for data source.
type DataSourcePatch struct {
- ID int
-
- // Standard fields
- // Value is assigned from the jwt subject field passed by the client.
- UpdaterID int
-
- // Domain specific fields
Username *string `jsonapi:"attr,username"`
Password *string `jsonapi:"attr,password"`
UseEmptyPassword *bool `jsonapi:"attr,useEmptyPassword"`
@@ -158,9 +111,3 @@ type DataSourcePatch struct {
Options *DataSourceOptions `jsonapi:"attr,options"`
Database *string `jsonapi:"attr,database"`
}
-
-// DataSourceDelete is the API message for deleting data sources.
-type DataSourceDelete struct {
- ID int
- InstanceID int
-}
diff --git a/server/database.go b/server/database.go
index 94f1d72407..027098e6a2 100644
--- a/server/database.go
+++ b/server/database.go
@@ -427,7 +427,6 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Database ID is not a number: %s", c.Param("databaseID"))).SetInternal(err)
}
-
dataSourceID, err := strconv.Atoi(c.Param("dataSourceID"))
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("Data source ID is not a number: %s", c.Param("dataSourceID"))).SetInternal(err)
@@ -440,23 +439,31 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
if database == nil {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Database not found with ID %d", databaseID))
}
-
- dataSourceFind := &api.DataSourceFind{
- ID: &dataSourceID,
+ instance, err := s.store.GetInstanceV2(ctx, &store.FindInstanceMessage{EnvironmentID: &database.EnvironmentID, ResourceID: &database.InstanceID})
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to get instance").SetInternal(err)
}
- dataSource, err := s.store.GetDataSource(ctx, dataSourceFind)
+ if instance == nil {
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance not found for database ID %d", databaseID))
+ }
+
+ composedInstance, err := s.store.GetInstanceByID(ctx, instance.UID)
if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch data source by ID %d", dataSourceID)).SetInternal(err)
+ return err
}
- if dataSource == nil {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Data source not found with ID %d", dataSourceID))
+ var composedDataSource *api.DataSource
+ for _, ds := range composedInstance.DataSourceList {
+ if ds.ID == dataSourceID {
+ composedDataSource = ds
+ break
+ }
}
- if dataSource.DatabaseID != databaseID {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("data source not found by ID %d and database ID %d", dataSourceID, databaseID))
+ if composedDataSource == nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "data source not found")
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, dataSource); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, composedDataSource); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal find data source response").SetInternal(err)
}
return nil
@@ -494,28 +501,45 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
}
}
- dataSourceCreate.CreatorID = c.Get(getPrincipalIDContextKey()).(int)
- dataSourceCreate.DatabaseID = databaseID
+ creatorID := c.Get(getPrincipalIDContextKey()).(int)
+ title := api.AdminDataSourceName
+ if dataSourceCreate.Type == api.RO {
+ title = api.ReadOnlyDataSourceName
+ }
+ dataSourceMessage := &store.DataSourceMessage{
+ Title: title,
+ Type: dataSourceCreate.Type,
+ Username: dataSourceCreate.Username,
+ Password: dataSourceCreate.Password,
+ SslCa: dataSourceCreate.SslCa,
+ SslCert: dataSourceCreate.SslCert,
+ SslKey: dataSourceCreate.SslKey,
+ Host: dataSourceCreate.Host,
+ Port: dataSourceCreate.Port,
+ Database: dataSourceCreate.Database,
+ SRV: dataSourceCreate.Options.SRV,
+ AuthenticationDatabase: dataSourceCreate.Options.AuthenticationDatabase,
+ }
+ if err := s.store.AddDataSourceToInstanceV2(ctx, instance.UID, creatorID, instance.EnvironmentID, instance.ResourceID, dataSourceMessage); err != nil {
+ return err
+ }
- dataSource, err := s.store.CreateDataSource(ctx, instance, dataSourceCreate)
+ composedInstance, err := s.store.GetInstanceByID(ctx, instance.UID)
if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to create data source").SetInternal(err)
+ return err
}
-
- if _, err := s.SchemaSyncer.SyncInstance(ctx, instance); err != nil {
- log.Warn("Failed to sync instance",
- zap.String("instance", instance.ResourceID),
- zap.Error(err))
+ var composedDataSource *api.DataSource
+ for _, ds := range composedInstance.DataSourceList {
+ if ds.Type == dataSourceCreate.Type {
+ composedDataSource = ds
+ break
+ }
}
- // Sync all databases in the instance asynchronously.
- updatedInstance, err := s.store.GetInstanceByID(ctx, instance.UID)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated instance %q", instance.Title)).SetInternal(err)
+ if composedDataSource == nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "data source not found")
}
- s.stateCfg.InstanceDatabaseSyncChan <- updatedInstance
-
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, dataSource); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, composedDataSource); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal create data source response").SetInternal(err)
}
return nil
@@ -549,16 +573,14 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
if instance == nil {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance not found for database ID %d", databaseID))
}
-
- dataSourceFind := &api.DataSourceFind{
- ID: &dataSourceID,
- DatabaseID: &databaseID,
- }
- dataSourceOld, err := s.store.GetDataSource(ctx, dataSourceFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find data source").SetInternal(err)
+ var dataSource *store.DataSourceMessage
+ for _, ds := range instance.DataSources {
+ if ds.UID == dataSourceID {
+ dataSource = ds
+ break
+ }
}
- if dataSourceOld == nil {
+ if dataSource == nil {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("data source not found by ID %d and database ID %d", dataSourceID, databaseID))
}
@@ -566,38 +588,69 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
if err := jsonapi.UnmarshalPayload(c.Request().Body, dataSourcePatch); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Malformed patch data source request").SetInternal(err)
}
- if dataSourceOld.Type == api.RO && !s.licenseService.IsFeatureEnabled(api.FeatureReadReplicaConnection) {
+ if dataSource.Type == api.RO && !s.licenseService.IsFeatureEnabled(api.FeatureReadReplicaConnection) {
if (dataSourcePatch.Host != nil && *dataSourcePatch.Host != "") || (dataSourcePatch.Port != nil && *dataSourcePatch.Port != "") {
return echo.NewHTTPError(http.StatusForbidden, api.FeatureReadReplicaConnection.AccessErrorMessage())
}
}
- dataSourcePatch.ID = dataSourceID
- dataSourcePatch.UpdaterID = c.Get(getPrincipalIDContextKey()).(int)
-
+ updateMessage := &store.UpdateDataSourceMessage{
+ UpdaterID: c.Get(getPrincipalIDContextKey()).(int),
+ InstanceUID: instance.UID,
+ EnvironmentID: instance.EnvironmentID,
+ InstanceID: instance.ResourceID,
+ Type: dataSource.Type,
+ Username: dataSourcePatch.Username,
+ Password: dataSourcePatch.Password,
+ SslCa: dataSourcePatch.SslCa,
+ SslCert: dataSourcePatch.SslCert,
+ SslKey: dataSourcePatch.SslKey,
+ Host: dataSourcePatch.Host,
+ Port: dataSourcePatch.Port,
+ }
+ if dataSourcePatch.Options != nil {
+ updateMessage.SRV = &dataSourcePatch.Options.SRV
+ updateMessage.AuthenticationDatabase = &dataSourcePatch.Options.AuthenticationDatabase
+ }
if dataSourcePatch.UseEmptyPassword != nil && *dataSourcePatch.UseEmptyPassword {
password := ""
- dataSourcePatch.Password = &password
+ updateMessage.Password = &password
}
- dataSourceNew, err := s.store.PatchDataSource(ctx, instance, dataSourcePatch)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to update data source with ID %d", dataSourceID)).SetInternal(err)
+ if err := s.store.UpdateDataSourceV2(ctx, updateMessage); err != nil {
+ return err
}
- if _, err := s.SchemaSyncer.SyncInstance(ctx, instance); err != nil {
- log.Warn("Failed to sync instance",
- zap.String("instance", instance.ResourceID),
- zap.Error(err))
+ if dataSource.Type == api.Admin {
+ if _, err := s.SchemaSyncer.SyncInstance(ctx, instance); err != nil {
+ log.Warn("Failed to sync instance",
+ zap.String("instance", instance.ResourceID),
+ zap.Error(err))
+ }
+ // Sync all databases in the instance asynchronously.
+ updatedInstance, err := s.store.GetInstanceByID(ctx, instance.UID)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated instance %q", instance.Title)).SetInternal(err)
+ }
+ s.stateCfg.InstanceDatabaseSyncChan <- updatedInstance
}
- // Sync all databases in the instance asynchronously.
- updatedInstance, err := s.store.GetInstanceByID(ctx, instance.UID)
+
+ composedInstance, err := s.store.GetInstanceByID(ctx, instance.UID)
if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf("Failed to fetch updated instance %q", instance.Title)).SetInternal(err)
+ return err
+ }
+ var composedDataSource *api.DataSource
+ for _, ds := range composedInstance.DataSourceList {
+ if ds.Type == dataSource.Type {
+ composedDataSource = ds
+ break
+ }
+ }
+ if composedDataSource == nil {
+ return echo.NewHTTPError(http.StatusBadRequest, "data source not found")
}
- s.stateCfg.InstanceDatabaseSyncChan <- updatedInstance
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
- if err := jsonapi.MarshalPayload(c.Response().Writer, dataSourceNew); err != nil {
+ if err := jsonapi.MarshalPayload(c.Response().Writer, composedDataSource); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal patch data source response").SetInternal(err)
}
return nil
@@ -630,27 +683,21 @@ func (s *Server) registerDatabaseRoutes(g *echo.Group) {
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Instance not found for database ID %d", databaseID))
}
- dataSourceFind := &api.DataSourceFind{
- ID: &dataSourceID,
- DatabaseID: &databaseID,
- }
- dataSource, err := s.store.GetDataSource(ctx, dataSourceFind)
- if err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to find data source").SetInternal(err)
+ var dataSource *store.DataSourceMessage
+ for _, ds := range instance.DataSources {
+ if ds.UID == dataSourceID {
+ dataSource = ds
+ break
+ }
}
if dataSource == nil {
- return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Data source not found by ID %d and database ID %d", dataSourceID, databaseID))
+ return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("data source not found by ID %d and database ID %d", dataSourceID, databaseID))
}
- // Only allow to delete ReadOnly data source at present.
- if dataSource.Type != api.RO {
- return echo.NewHTTPError(http.StatusForbidden, "Data source type is not read only")
+ if dataSource.Type == api.Admin {
+ return echo.NewHTTPError(http.StatusBadRequest, "admin data source cannot be deleted")
}
-
- if err := s.store.DeleteDataSource(ctx, instance, &api.DataSourceDelete{
- ID: dataSource.ID,
- InstanceID: instance.UID,
- }); err != nil {
- return echo.NewHTTPError(http.StatusInternalServerError, "Failed to delete data source").SetInternal(err)
+ if err := s.store.RemoveDataSourceV2(ctx, instance.UID, instance.EnvironmentID, instance.ResourceID, dataSource.Type); err != nil {
+ return err
}
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
diff --git a/store/cache.go b/store/cache.go
index 699414a552..c627a85a7e 100644
--- a/store/cache.go
+++ b/store/cache.go
@@ -19,8 +19,6 @@ const (
pipelineCacheNamespace cacheNamespace = "pl"
// issueCacheNamespace is the cache type of issues.
issueCacheNamespace cacheNamespace = "is"
- // dataSourceCacheNamespace is the cache type of data sources.
- dataSourceCacheNamespace cacheNamespace = "ds"
// approvalPolicyCacheNamespace is the cache type of approval policy.
approvalPolicyCacheNamespace cacheNamespace = "app"
)
diff --git a/store/data_source.go b/store/data_source.go
index 3c2a7a029e..c3022b5475 100644
--- a/store/data_source.go
+++ b/store/data_source.go
@@ -2,413 +2,14 @@ package store
import (
"context"
- "database/sql"
"fmt"
"strings"
"github.com/pkg/errors"
"github.com/bytebase/bytebase/api"
- "github.com/bytebase/bytebase/common"
)
-// dataSourceRaw is the store model for an DataSource.
-// Fields have exactly the same meanings as DataSource.
-type dataSourceRaw struct {
- ID int
-
- // Related fields
- InstanceID int
- DatabaseID int
-
- // Domain specific fields
- Name string
- Type api.DataSourceType
- Username string
- Password string
- SslCa string
- SslCert string
- SslKey string
- Host string
- Port string
- Options api.DataSourceOptions
- Database string
-}
-
-// toDataSource creates an instance of DataSource based on the dataSourceRaw.
-// This is intended to be called when we need to compose an DataSource relationship.
-func (raw *dataSourceRaw) toDataSource() *api.DataSource {
- return &api.DataSource{
- ID: raw.ID,
-
- // Related fields
- InstanceID: raw.InstanceID,
- DatabaseID: raw.DatabaseID,
-
- // Domain specific fields
- Name: raw.Name,
- Type: raw.Type,
- Username: raw.Username,
- Password: raw.Password,
- SslCa: raw.SslCa,
- SslCert: raw.SslCert,
- SslKey: raw.SslKey,
- Host: raw.Host,
- Port: raw.Port,
- Options: raw.Options,
- Database: raw.Database,
- }
-}
-
-// CreateDataSource creates an instance of DataSource.
-func (s *Store) CreateDataSource(ctx context.Context, instance *InstanceMessage, create *api.DataSourceCreate) (*api.DataSource, error) {
- dataSourceRaw, err := s.createDataSourceRaw(ctx, create)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to create data source with DataSourceCreate[%+v]", create)
- }
- s.instanceCache.Delete(getInstanceCacheKey(instance.EnvironmentID, instance.ResourceID))
- s.instanceIDCache.Delete(instance.UID)
- return composeDataSource(dataSourceRaw), nil
-}
-
-// GetDataSource gets an instance of DataSource.
-func (s *Store) GetDataSource(ctx context.Context, find *api.DataSourceFind) (*api.DataSource, error) {
- dataSourceRaw, err := s.getDataSourceRaw(ctx, find)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to get data source with DataSourceFind[%+v]", find)
- }
- if dataSourceRaw == nil {
- return nil, nil
- }
- return composeDataSource(dataSourceRaw), nil
-}
-
-// PatchDataSource patches an instance of DataSource.
-func (s *Store) PatchDataSource(ctx context.Context, instance *InstanceMessage, patch *api.DataSourcePatch) (*api.DataSource, error) {
- dataSourceRaw, err := s.patchDataSourceRaw(ctx, patch)
- if err != nil {
- return nil, errors.Wrapf(err, "failed to patch DataSource with DataSourcePatch[%+v]", patch)
- }
- s.instanceCache.Delete(getInstanceCacheKey(instance.EnvironmentID, instance.ResourceID))
- s.instanceIDCache.Delete(instance.UID)
- return composeDataSource(dataSourceRaw), nil
-}
-
-// DeleteDataSource deletes an existing dataSource by ID.
-func (s *Store) DeleteDataSource(ctx context.Context, instance *InstanceMessage, deleteDataSource *api.DataSourceDelete) error {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return FormatError(err)
- }
- defer tx.Rollback()
-
- if err := s.deleteDataSourceImpl(ctx, tx, deleteDataSource); err != nil {
- return FormatError(err)
- }
-
- if err := tx.Commit(); err != nil {
- return FormatError(err)
- }
-
- // Invalidate the cache.
- s.cache.DeleteCache(dataSourceCacheNamespace, deleteDataSource.InstanceID)
- s.instanceCache.Delete(getInstanceCacheKey(instance.EnvironmentID, instance.ResourceID))
- s.instanceIDCache.Delete(instance.UID)
- return nil
-}
-
-// private functions.
-func composeDataSource(raw *dataSourceRaw) *api.DataSource {
- return raw.toDataSource()
-}
-
-// createDataSourceRaw creates a new dataSource.
-func (s *Store) createDataSourceRaw(ctx context.Context, create *api.DataSourceCreate) (*dataSourceRaw, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- dataSource, err := s.createDataSourceImpl(ctx, tx, create)
- if err != nil {
- return nil, err
- }
-
- if err := tx.Commit(); err != nil {
- return nil, FormatError(err)
- }
- // Invalidate the cache.
- s.cache.DeleteCache(dataSourceCacheNamespace, dataSource.InstanceID)
-
- return dataSource, nil
-}
-
-// getDataSourceRaw retrieves a single dataSource based on find.
-// Returns ECONFLICT if finding more than 1 matching records.
-func (s *Store) getDataSourceRaw(ctx context.Context, find *api.DataSourceFind) (*dataSourceRaw, error) {
- tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- list, err := s.findDataSourceImpl(ctx, tx, find)
- if err != nil {
- return nil, err
- }
-
- if len(list) == 0 {
- return nil, nil
- } else if len(list) > 1 {
- return nil, &common.Error{Code: common.Conflict, Err: errors.Errorf("found %d data sources with filter %+v, expect 1", len(list), find)}
- }
- return list[0], nil
-}
-
-// patchDataSourceRaw updates an existing dataSource by ID.
-// Returns ENOTFOUND if dataSource does not exist.
-func (s *Store) patchDataSourceRaw(ctx context.Context, patch *api.DataSourcePatch) (*dataSourceRaw, error) {
- tx, err := s.db.BeginTx(ctx, nil)
- if err != nil {
- return nil, FormatError(err)
- }
- defer tx.Rollback()
-
- dataSource, err := s.patchDataSourceImpl(ctx, tx, patch)
- if err != nil {
- return nil, FormatError(err)
- }
-
- if err := tx.Commit(); err != nil {
- return nil, FormatError(err)
- }
- // Invalidate the cache.
- s.cache.DeleteCache(dataSourceCacheNamespace, dataSource.InstanceID)
-
- return dataSource, nil
-}
-
-// createDataSourceImpl creates a new dataSource.
-func (*Store) createDataSourceImpl(ctx context.Context, tx *Tx, create *api.DataSourceCreate) (*dataSourceRaw, error) {
- // Insert row into dataSource.
- query := `
- INSERT INTO data_source (
- creator_id,
- updater_id,
- instance_id,
- database_id,
- name,
- type,
- username,
- password,
- ssl_key,
- ssl_cert,
- ssl_ca,
- host,
- port,
- options,
- database
- )
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)
- RETURNING id, instance_id, database_id, name, type, username, password, ssl_key, ssl_cert, ssl_ca, host, port, options, database
- `
- var dataSourceRaw dataSourceRaw
- if err := tx.QueryRowContext(ctx, query,
- create.CreatorID,
- create.CreatorID,
- create.InstanceID,
- create.DatabaseID,
- create.Name,
- create.Type,
- create.Username,
- create.Password,
- create.SslKey,
- create.SslCert,
- create.SslCa,
- create.Host,
- create.Port,
- create.Options,
- create.Database,
- ).Scan(
- &dataSourceRaw.ID,
- &dataSourceRaw.InstanceID,
- &dataSourceRaw.DatabaseID,
- &dataSourceRaw.Name,
- &dataSourceRaw.Type,
- &dataSourceRaw.Username,
- &dataSourceRaw.Password,
- &dataSourceRaw.SslKey,
- &dataSourceRaw.SslCert,
- &dataSourceRaw.SslCa,
- &dataSourceRaw.Host,
- &dataSourceRaw.Port,
- &dataSourceRaw.Options,
- &dataSourceRaw.Database,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, common.FormatDBErrorEmptyRowWithQuery(query)
- }
- return nil, FormatError(err)
- }
- return &dataSourceRaw, nil
-}
-
-func (*Store) findDataSourceImpl(ctx context.Context, tx *Tx, find *api.DataSourceFind) ([]*dataSourceRaw, error) {
- // Build WHERE clause.
- where, args := []string{"TRUE"}, []interface{}{}
- if v := find.ID; v != nil {
- where, args = append(where, fmt.Sprintf("id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.InstanceID; v != nil {
- where, args = append(where, fmt.Sprintf("instance_id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.DatabaseID; v != nil {
- where, args = append(where, fmt.Sprintf("database_id = $%d", len(args)+1)), append(args, *v)
- }
- if v := find.Type; v != nil {
- where, args = append(where, fmt.Sprintf("type = $%d", len(args)+1)), append(args, api.DataSourceType(*v))
- }
-
- rows, err := tx.QueryContext(ctx, `
- SELECT
- id,
- instance_id,
- database_id,
- name,
- type,
- username,
- password,
- ssl_key,
- ssl_cert,
- ssl_ca,
- host,
- port,
- options,
- database
- FROM data_source
- WHERE `+strings.Join(where, " AND "),
- args...,
- )
- if err != nil {
- return nil, FormatError(err)
- }
- defer rows.Close()
-
- // Iterate over result set and deserialize rows into dataSourceRawList.
- var dataSourceRawList []*dataSourceRaw
- for rows.Next() {
- var dataSourceRaw dataSourceRaw
- if err := rows.Scan(
- &dataSourceRaw.ID,
- &dataSourceRaw.InstanceID,
- &dataSourceRaw.DatabaseID,
- &dataSourceRaw.Name,
- &dataSourceRaw.Type,
- &dataSourceRaw.Username,
- &dataSourceRaw.Password,
- &dataSourceRaw.SslKey,
- &dataSourceRaw.SslCert,
- &dataSourceRaw.SslCa,
- &dataSourceRaw.Host,
- &dataSourceRaw.Port,
- &dataSourceRaw.Options,
- &dataSourceRaw.Database,
- ); err != nil {
- return nil, FormatError(err)
- }
-
- dataSourceRawList = append(dataSourceRawList, &dataSourceRaw)
- }
- if err := rows.Err(); err != nil {
- return nil, FormatError(err)
- }
-
- return dataSourceRawList, nil
-}
-
-// patchDataSourceImpl updates a dataSource by ID. Returns the new state of the dataSource after update.
-func (*Store) patchDataSourceImpl(ctx context.Context, tx *Tx, patch *api.DataSourcePatch) (*dataSourceRaw, error) {
- // Build UPDATE clause.
- set, args := []string{"updater_id = $1"}, []interface{}{patch.UpdaterID}
- if v := patch.Username; v != nil {
- set, args = append(set, fmt.Sprintf("username = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.Password; v != nil {
- set, args = append(set, fmt.Sprintf("password = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.SslCa; v != nil {
- set, args = append(set, fmt.Sprintf("ssl_ca= $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.SslKey; v != nil {
- set, args = append(set, fmt.Sprintf("ssl_key= $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.SslCert; v != nil {
- set, args = append(set, fmt.Sprintf("ssl_cert= $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.Host; v != nil {
- set, args = append(set, fmt.Sprintf("host = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.Port; v != nil {
- set, args = append(set, fmt.Sprintf("port = $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.Options; v != nil {
- set, args = append(set, fmt.Sprintf("options= $%d", len(args)+1)), append(args, *v)
- }
- if v := patch.Database; v != nil {
- set, args = append(set, fmt.Sprintf("database = $%d", len(args)+1)), append(args, *v)
- }
- args = append(args, patch.ID)
-
- var dataSourceRaw dataSourceRaw
- // Execute update query with RETURNING.
- if err := tx.QueryRowContext(ctx, fmt.Sprintf(`
- UPDATE data_source
- SET `+strings.Join(set, ", ")+`
- WHERE id = $%d
- RETURNING id, instance_id, database_id, name, type, username, password, ssl_key, ssl_cert, ssl_ca, host, port, options, database
- `, len(args)),
- args...,
- ).Scan(
- &dataSourceRaw.ID,
- &dataSourceRaw.InstanceID,
- &dataSourceRaw.DatabaseID,
- &dataSourceRaw.Name,
- &dataSourceRaw.Type,
- &dataSourceRaw.Username,
- &dataSourceRaw.Password,
- &dataSourceRaw.SslKey,
- &dataSourceRaw.SslCert,
- &dataSourceRaw.SslCa,
- &dataSourceRaw.Host,
- &dataSourceRaw.Port,
- &dataSourceRaw.Options,
- &dataSourceRaw.Database,
- ); err != nil {
- if err == sql.ErrNoRows {
- return nil, &common.Error{Code: common.NotFound, Err: errors.Errorf("DataSource not found with ID %d", patch.ID)}
- }
- return nil, FormatError(err)
- }
- return &dataSourceRaw, nil
-}
-
-// deleteDataSourceImpl permanently deletes a dataSource by ID.
-func (*Store) deleteDataSourceImpl(ctx context.Context, tx *Tx, delete *api.DataSourceDelete) error {
- if _, err := tx.ExecContext(ctx, `DELETE FROM data_source WHERE id = $1`, delete.ID); err != nil {
- return FormatError(err)
- }
- return nil
-}
-
-// clearDataSourceImpl deletes dataSources by instance id and database id.
-func (*Store) clearDataSourceImpl(ctx context.Context, tx *Tx, instanceID, databaseID int) error {
- if _, err := tx.ExecContext(ctx, `DELETE FROM data_source WHERE instance_id = $1 AND database_id = $2`, instanceID, databaseID); err != nil {
- return FormatError(err)
- }
- return nil
-}
-
// DataSourceMessage is the message for data source.
type DataSourceMessage struct {
Title string
@@ -674,3 +275,11 @@ func (*Store) addDataSourceToInstanceImplV2(ctx context.Context, tx *Tx, instanc
return nil
}
+
+// clearDataSourceImpl deletes dataSources by instance id and database id.
+func (*Store) clearDataSourceImpl(ctx context.Context, tx *Tx, instanceID, databaseID int) error {
+ if _, err := tx.ExecContext(ctx, `DELETE FROM data_source WHERE instance_id = $1 AND database_id = $2`, instanceID, databaseID); err != nil {
+ return FormatError(err)
+ }
+ return nil
+}
diff --git a/store/instance.go b/store/instance.go
index 59f1300dd1..21551c8362 100644
--- a/store/instance.go
+++ b/store/instance.go
@@ -87,10 +87,6 @@ func (s *Store) composeInstance(ctx context.Context, instance *InstanceMessage)
Name: ds.Title,
Type: ds.Type,
Username: ds.Username,
- Password: ds.Password,
- SslCa: ds.SslCa,
- SslCert: ds.SslCert,
- SslKey: ds.SslKey,
Host: ds.Host,
Port: ds.Port,
Options: api.DataSourceOptions{SRV: ds.SRV, AuthenticationDatabase: ds.AuthenticationDatabase},
diff --git a/tests/data_source_test.go b/tests/data_source_test.go
index fe87a4b87e..820422c52b 100644
--- a/tests/data_source_test.go
+++ b/tests/data_source_test.go
@@ -52,16 +52,14 @@ func TestDataSource(t *testing.T) {
instanceID := instance.ID
// create read-only data source.
- err = ctl.createDataSource(api.DataSourceCreate{
- InstanceID: instanceID,
- DatabaseID: adminDataSource.DatabaseID,
- Name: api.ReadOnlyDataSourceName,
- Type: api.RO,
- Username: "ro_ds",
- Password: "",
- SslCa: "",
- SslCert: "",
- SslKey: "",
+ err = ctl.createDataSource(adminDataSource.DatabaseID, api.DataSourceCreate{
+ Name: api.ReadOnlyDataSourceName,
+ Type: api.RO,
+ Username: "ro_ds",
+ Password: "",
+ SslCa: "",
+ SslCert: "",
+ SslKey: "",
})
a.NoError(err)
@@ -77,8 +75,7 @@ func TestDataSource(t *testing.T) {
dataSourceNewName := "updated_ro_ds"
dataSourceNewPassword := "bytebase"
// create read-only data source.
- err = ctl.patchDataSource(adminDataSource.DatabaseID, api.DataSourcePatch{
- ID: readOnlyDataSource.ID,
+ err = ctl.patchDataSource(adminDataSource.DatabaseID, readOnlyDataSource.ID, api.DataSourcePatch{
Username: &dataSourceNewName,
Password: &dataSourceNewPassword,
})
@@ -90,8 +87,7 @@ func TestDataSource(t *testing.T) {
// update read-only data source read replica fields without enterprise license.
err = ctl.removeLicense()
a.NoError(err)
- err = ctl.patchDataSource(adminDataSource.DatabaseID, api.DataSourcePatch{
- ID: readOnlyDataSource.ID,
+ err = ctl.patchDataSource(adminDataSource.DatabaseID, readOnlyDataSource.ID, api.DataSourcePatch{
Host: &dataSourceNewHost,
Port: &dataSourceNewPort,
})
@@ -99,8 +95,7 @@ func TestDataSource(t *testing.T) {
err = ctl.setLicense()
a.NoError(err)
- err = ctl.patchDataSource(adminDataSource.DatabaseID, api.DataSourcePatch{
- ID: readOnlyDataSource.ID,
+ err = ctl.patchDataSource(adminDataSource.DatabaseID, readOnlyDataSource.ID, api.DataSourcePatch{
Host: &dataSourceNewHost,
Port: &dataSourceNewPort,
})
diff --git a/tests/database.go b/tests/database.go
index 7578d3266b..8ab5583f26 100644
--- a/tests/database.go
+++ b/tests/database.go
@@ -220,13 +220,13 @@ func marshalLabels(labelMap map[string]string, environmentID string) (string, er
return string(labels), nil
}
-func (ctl *controller) createDataSource(dataSourceCreate api.DataSourceCreate) error {
+func (ctl *controller) createDataSource(databaseID int, dataSourceCreate api.DataSourceCreate) error {
buf := new(bytes.Buffer)
if err := jsonapi.MarshalPayload(buf, &dataSourceCreate); err != nil {
return errors.Wrap(err, "failed to marshal dataSourceCreate")
}
- body, err := ctl.post(fmt.Sprintf("/database/%d/data-source", dataSourceCreate.DatabaseID), buf)
+ body, err := ctl.post(fmt.Sprintf("/database/%d/data-source", databaseID), buf)
if err != nil {
return err
}
@@ -238,13 +238,13 @@ func (ctl *controller) createDataSource(dataSourceCreate api.DataSourceCreate) e
return nil
}
-func (ctl *controller) patchDataSource(databaseID int, dataSourcePatch api.DataSourcePatch) error {
+func (ctl *controller) patchDataSource(databaseID, dataSourceID int, dataSourcePatch api.DataSourcePatch) error {
buf := new(bytes.Buffer)
if err := jsonapi.MarshalPayload(buf, &dataSourcePatch); err != nil {
return errors.Wrap(err, "failed to marshal dataSourcePatch")
}
- body, err := ctl.patch(fmt.Sprintf("/database/%d/data-source/%d", databaseID, dataSourcePatch.ID), buf)
+ body, err := ctl.patch(fmt.Sprintf("/database/%d/data-source/%d", databaseID, dataSourceID), buf)
if err != nil {
return err
}