mongodb

package
v1.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 39 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package mongodb is the MongoDB extension (SPEC §10.22, D23): connections on the shared "Databases" view (extensions/internal/dbconn), the explorer of databases, collections, indexes and the sampled schema, and the playground language whose parser is the package playground.

How it fits the shared view

The extension "Databases" shows the connections; this extension gives the one dbconn.Hub a Driver for the engine "mongodb". The hub asks the driver to connect, to list what is below a connection or a node (the nodes carry what the driver needs in their Data), and for the entries of a node's context menu. The servers that are open belong to one manager that every window tab's instance of the extension shares, as the hub is shared.

The server behind an interface

Everything the explorer asks of a server goes through Backend, so that the explorer is tested against a fake. The real Backend is a client of the official driver (go.mongodb.org/mongo-driver/v2); a test of it against a server of its own is in the files with the build tag emetos_docker.

Passwords

A password is never in a connection string of ours: the hub finds it (the environment, the memory, the keyring, D24) and gives it to Dial, which sets it on the credential of the driver's options. The password a user pastes inside a connection string moves out of the string to the keyring when the connection is saved (dbconn.StripURLPassword).

Index

Constants

View Source
const (
	// ID is the id of the extension.
	ID = "emetos.mongodb"
	// EngineID is the engine this extension registers with the shared view; it is the "engine" of a connection in the file.
	EngineID = "mongodb"
	// LanguageID is the language of the playgrounds (the .mongodb files).
	LanguageID = "mongodb"
	// NewPlaygroundCommand opens an untitled playground. It takes no argument, or {"connection": id, "database": name,
	// "collection": name} to start from a place of the explorer.
	NewPlaygroundCommand = "mongodb.newPlayground"
	// SchemaSampleSizeSetting is how many documents are read to sample the schema of a collection.
	SchemaSampleSizeSetting = "mongodb.schemaSampleSize"

	// ConnectedTopic and DisconnectedTopic are the events of a connection that opened or closed; the data is {"connection": id}.
	ConnectedTopic    = ID + ".connected"
	DisconnectedTopic = ID + ".disconnected"
)

The ids of the extension (SPEC §10.22).

View Source
const (
	// RunCommand runs the selection or the statement under the cursor of the active playground (Ctrl+Enter) and RunAllCommand every
	// statement of it (Ctrl+Shift+Enter).
	RunCommand    = "mongodb.run"
	RunAllCommand = "mongodb.runAll"
	// CancelCommand stops the statement that runs.
	CancelCommand = "mongodb.cancel"
	// SelectConnectionCommand binds the active playground to a connection and a database.
	SelectConnectionCommand = "mongodb.selectConnection"
	// OpenCollectionCommand shows the first documents of a collection in the results; its argument is {"connection": id,
	// "database": name, "collection": name}.
	OpenCollectionCommand = "mongodb.openCollection"
	// EditDocumentCommand opens the selected document of the results as Extended JSON, DeleteDocumentCommand deletes it after asking,
	// and SaveDocumentCommand saves the document of the active editor to the server (Ctrl+S in a document that is being edited).
	EditDocumentCommand   = "mongodb.editDocument"
	DeleteDocumentCommand = "mongodb.deleteDocument"
	SaveDocumentCommand   = "mongodb.saveDocument"
	// CopyDocumentCommand copies the selected document, or the documents of the shown set, as Extended JSON.
	CopyDocumentCommand = "mongodb.copyDocument"
	// ViewID is the panel tab "MongoDB Results".
	ViewID = ID + ".results"
	// PageSizeSetting is how many documents a cursor gives each time; ConfirmDestructiveSetting asks before drop, dropDatabase,
	// deleteMany({}) and updateMany({}, ...).
	PageSizeSetting           = "mongodb.pageSize"
	ConfirmDestructiveSetting = "mongodb.confirmDestructive"
	// RunningKey is true while the playground whose results show runs a statement; EditingKey while the active editor is a document
	// that is being edited.
	RunningKey = ID + ".running"
	EditingKey = ID + ".editingDocument"
	// CommandFinishedTopic is published when a statement ends: {"connection": id, "ok": bool, "millis": n}. It has no text of the
	// statement and no value.
	CommandFinishedTopic = ID + ".commandFinished"
	// ProblemsOwner is the owner of the markers of the errors of statements.
	ProblemsOwner = "mongodb"
)

The ids of the commands, the view, the settings, the context keys and the events of the playgrounds (SPEC §10.22 "Playgrounds", "Results", "Editing a document", "Safety").

View Source
const (
	// ModeTree shows expandable fields with their BSON types, ModeJSON the documents as Extended JSON and ModeTable the top-level
	// fields as columns.
	ModeTree  viewMode = "tree"
	ModeJSON  viewMode = "json"
	ModeTable viewMode = "table"
)

The three views of a result (SPEC §10.22 "Results").

View Source
const DefaultDatabase = "test"

DefaultDatabase is the database a statement runs on when the playground, the editor and the connection name none (the shell's "test").

Variables

This section is empty.

Functions

func DocumentText

func DocumentText(d bson.D) (string, error)

DocumentText writes a document as relaxed Extended JSON, indented with two spaces: the text of the JSON view and of the editor of a document (SPEC §10.22 "Results", "Editing a document").

func DocumentsText

func DocumentsText(docs []bson.D) (string, error)

DocumentsText writes documents as one JSON array, one document after the other, for the JSON view.

func FactoryOf

func FactoryOf(hub *dbconn.Hub, opts ...Options) extension.Factory

FactoryOf makes the Factory of the extension over the hub that the database extensions share (extensions.All makes one hub and gives it to each). Every instance the factory makes (one for each window tab) shares the servers that are open.

func FormatBytes

func FormatBytes(n int64) string

FormatBytes writes a size in bytes as the explorer shows it: "512 B", "1.5 KiB", "12.0 MiB".

func FormatCount

func FormatCount(n int64) string

FormatCount writes a number of documents with thousands separators and the word: "1 document", "12,345 documents".

func IDText

func IDText(id any) string

IDText writes an _id as the shell does: ObjectId("..."), "text", 12.

func Merge

func Merge(original, edited bson.D) bson.D

Merge makes the document to store from the stored one and the edited text: the fields the edit left as they were keep their stored values (so a long, a date or a decimal that the relaxed text shows as a plain number keeps its type), the changed ones take the edited value, and the order of the edited document is kept.

func ParseDocument

func ParseDocument(text string) (bson.D, error)

ParseDocument reads the text of an edited document, Extended JSON (relaxed or canonical), into a document.

func ServerError

func ServerError(err error) (code int, name string)

ServerError reads the code and the name of the code that the server gave in the error of a call; zero and empty when it gave none.

Types

type Backend

type Backend interface {
	// Databases lists the databases the user may see.
	Databases(ctx context.Context) ([]DatabaseInfo, error)
	// Collections lists the collections, views and time series collections of a database.
	Collections(ctx context.Context, database string) ([]CollectionInfo, error)
	// EstimatedCount is the estimated number of documents of a collection, from its metadata.
	EstimatedCount(ctx context.Context, database, collection string) (int64, error)
	// Indexes lists the indexes of a collection.
	Indexes(ctx context.Context, database, collection string) ([]IndexInfo, error)
	// Sample reads up to n documents chosen at random from a collection or a view.
	Sample(ctx context.Context, database, collection string, n int) ([]bson.D, error)
	// Exec runs a call of a playground (SPEC §10.22 "Playgrounds"). A call that reads with a cursor answers with its first page of at
	// most pageSize documents and the cursor that reads the rest, if there is a rest; any other call answers with all of its
	// documents. A failure of the server has the code and the name of the code in the metadata of its error (ServerError).
	Exec(ctx context.Context, call Call, pageSize int) (Reply, error)
	// Close ends the connection to the server.
	Close(ctx context.Context) error
}

Backend is what the explorer needs of one open server: the driver behind an interface, so that the explorer is tested against a fake (SPEC §10.22). Every call takes a context and ends with it.

type BulkOp

type BulkOp struct {
	// Kind is insertOne, updateOne, updateMany, replaceOne, deleteOne or deleteMany.
	Kind string
	// Filter selects the documents of an update, replace or delete.
	Filter bson.D
	// Doc is the document of insertOne and the replacement of replaceOne.
	Doc bson.D
	// Update is the update document (bson.D) or pipeline (bson.A).
	Update       any
	Upsert       bool
	ArrayFilters bson.A
	Collation    bson.D
	Hint         any
}

BulkOp is one operation of a bulkWrite.

type Call

type Call struct {
	Kind CallKind
	// Database is the database the call runs on; Collection the collection, empty for a command, a show and a call on the server.
	Database, Collection string
	// Filter, Projection and Sort are the documents of a find, and of the update, delete and count calls (Filter).
	Filter, Projection, Sort bson.D
	// Skip and Limit are those of a find; zero is none.
	Skip, Limit int64
	// Pipeline is the pipeline of an aggregation.
	Pipeline bson.A
	// Docs are the documents of an insert (one for insertOne).
	Docs []bson.D
	// Update is the update document (bson.D) or the pipeline (bson.A) of an update.
	Update any
	// Replacement is the document of replaceOne.
	Replacement bson.D
	// Field is the field of distinct.
	Field string
	// Command is the command document of CallCommand.
	Command bson.D
	// Ops are the operations of a bulkWrite.
	Ops []BulkOp
	// Options are the options the statement gave.
	Options CallOptions
}

Call is one request to the server, as a playground statement translates to it. It holds no connection and no driver type besides the values of the bson package, so that the translation is tested without a server and a fake Backend can answer it.

func (Call) Editable

func (c Call) Editable() bool

Editable tells whether the documents the call returns can be edited and deleted one by one: they are whole documents of a collection (a find without a projection), so that replacing one with the edited text loses nothing.

func (Call) Title

func (c Call) Title() string

Title is the name of the call for a tab: orders.find, show dbs, runCommand.

type CallKind

type CallKind string

CallKind is what a Call asks of the server.

const (
	// CallFind reads documents with a cursor (find, findOne is CallFindOne).
	CallFind CallKind = "find"
	// CallFindOne reads the first document that matches.
	CallFindOne CallKind = "findOne"
	// CallAggregate runs a pipeline and reads its documents with a cursor.
	CallAggregate CallKind = "aggregate"
	// CallCountDocuments counts the documents that match a filter (the count() of a find too).
	CallCountDocuments CallKind = "countDocuments"
	// CallEstimatedCount reads the estimated number of documents from the metadata of the collection.
	CallEstimatedCount CallKind = "estimatedDocumentCount"
	// CallDistinct lists the distinct values of a field.
	CallDistinct CallKind = "distinct"
	// CallInsertOne, CallInsertMany, CallUpdateOne, CallUpdateMany, CallReplaceOne, CallDeleteOne, CallDeleteMany and CallBulkWrite
	// change the documents of a collection.
	CallInsertOne  CallKind = "insertOne"
	CallInsertMany CallKind = "insertMany"
	CallUpdateOne  CallKind = "updateOne"
	CallUpdateMany CallKind = "updateMany"
	CallReplaceOne CallKind = "replaceOne"
	CallDeleteOne  CallKind = "deleteOne"
	CallDeleteMany CallKind = "deleteMany"
	CallBulkWrite  CallKind = "bulkWrite"
	// CallGetIndexes lists the indexes of a collection.
	CallGetIndexes CallKind = "getIndexes"
	// CallCommand runs a command document on a database (db.runCommand, db.adminCommand; createIndex, dropIndex and drop are
	// commands too).
	CallCommand CallKind = "command"
	// CallShowDatabases and CallShowCollections are "show dbs" and "show collections".
	CallShowDatabases   CallKind = "showDatabases"
	CallShowCollections CallKind = "showCollections"
)

The kinds of call, one for each thing a playground can ask (SPEC §10.22 "Playgrounds").

type CallOptions

type CallOptions struct {
	// Upsert makes an update or a replace insert when nothing matches.
	Upsert bool
	// Unordered makes insertMany and bulkWrite go on after an error (the default is ordered, as in the shell).
	Unordered bool
	// ArrayFilters are the filters of an update that names array elements.
	ArrayFilters bson.A
	// Collation is the collation document; Hint is the name of an index or its keys; Comment and Let are passed as they are.
	Collation bson.D
	Hint      any
	Comment   any
	Let       bson.D
	// AllowDiskUse lets an aggregation write to temporary files.
	AllowDiskUse bool
	// BypassValidation skips the validation rules of the collection.
	BypassValidation bool
	// MaxTime ends the call when the server takes longer (maxTimeMS); zero is no limit.
	MaxTime time.Duration
	// CountLimit and CountSkip are the limit and skip options of countDocuments.
	CountLimit, CountSkip int64
}

CallOptions are the options of a call that a playground may give as the last argument of a method.

type Change

type Change struct {
	Kind ChangeKind
	// Path is the name of the field, a.b.c for a field of a document inside a document; an array is compared whole, as one field.
	Path string
	// Old and New are the values as a line of JSON, cut at 60 characters; empty for an added and a removed field.
	Old, New string
}

Change is a field that differs.

func Diff

func Diff(original, edited bson.D) []Change

Diff lists the fields that differ between the stored document and the edited one, comparing the values as relaxed Extended JSON, so that an int32 and an int64 of the same number are the same. Documents inside documents are compared field by field.

func (Change) String

func (c Change) String() string

String writes the change on one line: "~ qty: 2 -> 3", "+ note: \"x\"", "- tags".

type ChangeKind

type ChangeKind string

ChangeKind says how a field differs between the stored document and the edited one.

const (
	// Changed is a field whose value is different.
	Changed ChangeKind = "~"
	// Added is a field the edited document has and the stored one does not.
	Added ChangeKind = "+"
	// Removed is a field the stored document has and the edited one does not.
	Removed ChangeKind = "-"
)

The kinds of change.

type Class

type Class int

Class says what a call does to the data, for the read-only check and the confirmation.

const (
	// ClassRead only reads.
	ClassRead Class = iota
	// ClassWrite changes data or the structure of a collection.
	ClassWrite
	// ClassDestructive can lose a lot of data: drop, dropDatabase, deleteMany({}) and updateMany({}, ...).
	ClassDestructive
)

The classes of call.

type CollectionInfo

type CollectionInfo struct {
	Name string
	Kind CollectionKind
	// ViewOn is the collection a view reads from.
	ViewOn string
}

CollectionInfo is a collection of a database.

type CollectionKind

type CollectionKind string

CollectionKind is what a collection of the server is.

const (
	// KindCollection is an ordinary collection.
	KindCollection CollectionKind = "collection"
	// KindView is a view: a pipeline over another collection.
	KindView CollectionKind = "view"
	// KindTimeSeries is a time series collection.
	KindTimeSeries CollectionKind = "timeseries"
)

The kinds of collection.

type Cursor

type Cursor interface {
	// Next reads up to n more documents. done is true when the cursor has nothing more and is closed.
	Next(ctx context.Context, n int) (docs []bson.D, done bool, err error)
	// Close ends the cursor on the server; closing a cursor that is done does nothing.
	Close(ctx context.Context) error
}

Cursor reads the documents that a call left on the server, a page at a time.

type DatabaseInfo

type DatabaseInfo struct {
	Name string
	// SizeOnDisk is in bytes; Empty says the database has no data.
	SizeOnDisk int64
	Empty      bool
}

DatabaseInfo is a database of the server.

type Dialer

type Dialer interface {
	// Dial connects as the connection says, with the password (empty for none, already found by the hub), and checks that the
	// server answers.
	Dial(ctx context.Context, c dbconn.Connection, password string) (Backend, error)
}

Dialer opens a Backend. The real one speaks to a server with the official driver; the tests give a fake.

type DocSet

type DocSet struct {
	// Title is the name of the call that made it ("orders.find").
	Title string
	// Call is the call, for fetching more and for deciding whether its documents can be edited.
	Call Call
	// Docs are the documents read so far.
	Docs []bson.D
	// Cursor reads more documents while it is not nil.
	Cursor Cursor
	// PageSize is how many documents a read takes.
	PageSize int
	// Editable says that the documents are whole documents of Call.Database.Call.Collection, so that they can be edited and deleted.
	Editable bool
	// Truncated says that reading stopped at maxSetDocs.
	Truncated bool
	// OnDrop, when set, is called with the cursor when the set lets go of it (it ran dry, or the set was released), so that its
	// owner stops keeping track of it.
	OnDrop func(Cursor)
}

DocSet is a result of documents: those read so far, and the cursor that reads more.

func (*DocSet) Append

func (s *DocSet) Append(docs []bson.D, done bool)

Append adds the documents a read brought; done says the cursor has no more.

func (*DocSet) More

func (s *DocSet) More() bool

More tells whether a read can bring more documents.

func (*DocSet) Release

func (s *DocSet) Release()

Release closes the cursor of the set, in the background, and forgets it.

type Extension

type Extension struct {
	// contains filtered or unexported fields
}

Extension is the MongoDB extension in one window tab.

func (*Extension) Activate

func (e *Extension) Activate(ctx context.Context, api extension.API) error

Activate implements extension.Extension: it registers the driver of the engine with the shared hub.

func (*Extension) Manifest

func (*Extension) Manifest() extension.Manifest

Manifest implements extension.Extension.

type IndexInfo

type IndexInfo struct {
	Name string
	// Keys are the indexed fields in order, with 1, -1 or the name of a special index ("text", "2dsphere", "hashed").
	Keys bson.D
	// Unique and Sparse are the flags of the index; TTLSeconds is the expireAfterSeconds of a TTL index, or nil.
	Unique, Sparse bool
	TTLSeconds     *int32
}

IndexInfo is an index of a collection.

type Options

type Options struct {
	// Dialer opens the servers; the official driver when nil. A test gives a fake.
	Dialer Dialer
}

Options configure the extension. The zero value is the real one.

type Reply

type Reply struct {
	// Docs are the documents of the first page of a call that reads with a cursor, and all of the documents of any other call: the
	// documents of a command's answer, the result of a write as a document (acknowledged, insertedId, matchedCount...), a count as
	// {count: n}, the values of distinct as {value: v}.
	Docs []bson.D
	// Cursor reads the rest while it is not nil.
	Cursor Cursor
	// Write is set by a call that writes.
	Write *WriteSummary
}

Reply is the answer to a call.

type RunError

type RunError struct {
	// Message is what the server or Emetos said.
	Message string
	// Code and CodeName are those of the server's error; zero and empty when the failure was not the server's.
	Code     int
	CodeName string
	// Tag is the tag of the error of Emetos that carried it (MongoRun*, MongoReadFailed...).
	Tag string
}

RunError is why a statement failed.

func (*RunError) Text

func (e *RunError) Text() string

Text writes the error for a person: "Error 11000 (DuplicateKey): E11000 duplicate key ...", or the message alone.

type RunItem

type RunItem struct {
	// Text is the source of the statement, for the Messages tab.
	Text string
	// Span is where it is in the playground, for the place of an error.
	Span playground.Span
	// Statement is the statement the parser made.
	Statement playground.Statement
}

RunItem is a statement of a playground that is about to run, with the text it was read from.

type RunOptions

type RunOptions struct {
	// Database is the database the first statement runs on; DefaultDatabase when empty.
	Database string
	// PageSize is how many documents a read takes.
	PageSize int
	// Started is called before statement i begins; Finished with its result. Both are called on the goroutine of the run.
	Started  func(i int, item RunItem)
	Finished func(res *StepResult)
}

RunOptions say how a run goes.

type Safety

type Safety struct {
	Class Class
	// Verb names the call for a message: "deleteMany", "drop".
	Verb string
	// Why is the short text of a destructive call: "deleteMany({})", "dropDatabase".
	Why string
}

Safety is what Classify says of a call.

func Classify

func Classify(c Call) Safety

Classify says what a call does to the data: it only reads, it writes, or it can lose a lot of data (SPEC §10.22 "Safety": drop, dropDatabase, deleteMany({}) and updateMany({}, ...)). A command is a read only when it is on the list of commands that read.

func (Safety) Writes

func (s Safety) Writes() bool

Writes tells whether the call is not a read.

type Schema

type Schema struct {
	// Documents is the size of the sample.
	Documents int
	// Fields are the top-level fields, in the order they were first seen.
	Fields []*SchemaField
	// MoreFields says that fields were left out at the top level.
	MoreFields bool
}

Schema is what a sample of documents shows about a collection.

func InferSchema

func InferSchema(docs []bson.D) *Schema

InferSchema reads the fields and their types out of a sample of documents.

type SchemaField

type SchemaField struct {
	// Name is the key; Path is the dotted path from the top of the document.
	Name, Path string
	// Count is how many documents of the sample had the field.
	Count int
	// Types counts the BSON types of the values ("string", "int", "null", "object", "array").
	Types map[string]int
	// ElementTypes counts the types of the items of the arrays, when the field was an array.
	ElementTypes map[string]int
	// Children are the fields of the documents inside this field (or inside the arrays of it), in the order they were first seen.
	Children []*SchemaField
	// MoreFields says that fields were left out at this level (SchemaMaxFields).
	MoreFields bool
	// contains filtered or unexported fields
}

SchemaField is a field found in the sample, with the types its values had and the fields of the documents inside it.

func (*SchemaField) Percent

func (f *SchemaField) Percent(sample int) int

Percent is how much of the sample had the field, of the given size of the sample: the whole numbers 1 to 100 (a field in one document of many is not shown as 0).

func (*SchemaField) TypesText

func (f *SchemaField) TypesText() string

TypesText writes the types of the field in order of how often they were seen: "string", "string | null", "array<object>".

type Step

type Step struct {
	// Use is the database that "use" selects; empty for a call.
	Use string
	// Call is the request to the server; nil for "use".
	Call *Call
}

Step is a statement of a playground as the runner does it: a change of the current database, or a call to the server.

func Translate

func Translate(st playground.Statement, db string) (Step, error)

Translate turns a statement into the step the runner does. db is the database the statement runs on ("use" before it, else the editor's, else the connection's); empty means DefaultDatabase. The error has a tag MongoRun*.

type StepResult

type StepResult struct {
	Item RunItem
	// Database is the database the statement ran on.
	Database string
	// Use is the database a "use" statement selected.
	Use string
	// Call is the call that was made; nil for "use" and for a statement that could not be translated.
	Call *Call
	// Sets are the documents the statement returned: one set for a call that has documents, none otherwise.
	Sets []*DocSet
	// Write says what a call that writes did.
	Write *WriteSummary
	// Message is the line the Messages tab shows when the statement worked.
	Message string
	// Err is why the statement failed; Cancelled that the user stopped it.
	Err       *RunError
	Cancelled bool
	Elapsed   time.Duration
}

StepResult is what one statement of a run gave.

func Run

func Run(ctx context.Context, b Backend, items []RunItem, opts RunOptions) []*StepResult

Run does the statements one after the other on the server, stopping at the first one that fails or is cancelled. It returns the results of the statements that were done. ctx ends the run: the statement that is running is cancelled.

type WriteSummary

type WriteSummary struct {
	Inserted, Matched, Modified, Upserted, Deleted int64
}

WriteSummary counts what a call that writes did.

Directories

Path Synopsis
Package playground reads the playgrounds of the MongoDB extension (SPEC §10.22): the .mongodb files, a subset of the mongosh syntax that Emetos parses and runs itself, because Emetos has no JavaScript engine.
Package playground reads the playgrounds of the MongoDB extension (SPEC §10.22): the .mongodb files, a subset of the mongosh syntax that Emetos parses and runs itself, because Emetos has no JavaScript engine.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL