Skip to content

Commit

Permalink
Allow multiple queries to create a db
Browse files Browse the repository at this point in the history
  • Loading branch information
flimzy committed Feb 11, 2024
1 parent 7b93e12 commit b3c84ac
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
8 changes: 4 additions & 4 deletions x/sqlite/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@

package sqlite

const (
schema = `CREATE TABLE %q (
var schema = []string{
`CREATE TABLE %q (
seq INTEGER PRIMARY KEY,
id TEXT NOT NULL,
rev_id INTEGER NOT NULL DEFAULT 1,
rev TEXT NOT NULL,
doc BLOB NOT NULL,
deleted BOOLEAN NOT NULL DEFAULT FALSE,
UNIQUE(id, rev_id, rev)
)`
)
)`,
}
26 changes: 17 additions & 9 deletions x/sqlite/sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,17 +115,25 @@ func (c *client) CreateDB(ctx context.Context, name string, _ driver.Options) er
if !validDBNameRE.MatchString(name) {
return &internal.Error{Status: http.StatusBadRequest, Message: "invalid database name"}
}
_, err := c.db.ExecContext(ctx, fmt.Sprintf(schema, name))
if err == nil {
return nil
tx, err := c.db.BeginTx(ctx, nil)
if err != nil {
return err

Check warning on line 120 in x/sqlite/sqlite.go

View check run for this annotation

Codecov / codecov/patch

x/sqlite/sqlite.go#L120

Added line #L120 was not covered by tests
}
sqliteErr := new(sqlite.Error)
if errors.As(err, &sqliteErr) &&
sqliteErr.Code() == codeSQLiteError &&
strings.Contains(sqliteErr.Error(), "already exists") {
return &internal.Error{Status: http.StatusPreconditionFailed, Message: "database already exists"}
defer tx.Rollback()
for _, query := range schema {
_, err := tx.ExecContext(ctx, fmt.Sprintf(query, name))
if err == nil {
continue
}
sqliteErr := new(sqlite.Error)
if errors.As(err, &sqliteErr) &&
sqliteErr.Code() == codeSQLiteError &&
strings.Contains(sqliteErr.Error(), "already exists") {
return &internal.Error{Status: http.StatusPreconditionFailed, Message: "database already exists"}
}
return err

Check warning on line 134 in x/sqlite/sqlite.go

View check run for this annotation

Codecov / codecov/patch

x/sqlite/sqlite.go#L134

Added line #L134 was not covered by tests
}
return err
return tx.Commit()
}

func (c *client) DestroyDB(ctx context.Context, name string, _ driver.Options) error {
Expand Down

0 comments on commit b3c84ac

Please sign in to comment.