mongodriver

package module
v0.0.0-...-4b5891b Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Overview

Package mongodriver provides a database/sql compatible driver for MongoDB. It accepts JSON query DSL generated by GraphJin's MongoDB dialect and translates it to MongoDB aggregation pipelines.

Index

Constants

View Source
const (
	OpAggregate         = "aggregate"
	OpMultiAggregate    = "multi_aggregate"
	OpFind              = "find"
	OpFindOne           = "findOne"
	OpInsertOne         = "insertOne"
	OpInsertMany        = "insertMany"
	OpUpdateOne         = "updateOne"
	OpUpdateMany        = "updateMany"
	OpDeleteOne         = "deleteOne"
	OpDeleteMany        = "deleteMany"
	OpNestedInsert      = "nested_insert"
	OpNestedUpdate      = "nested_update"
	OpIntrospectInfo    = "introspect_info"
	OpIntrospectColumns = "introspect_columns"
	OpIntrospectFuncs   = "introspect_functions"
	OpEmpty             = "empty" // For dropped root selections (@add/@remove directives)
	OpNull              = "null"  // For nulled selections (@skip/@include directives)
)

Supported operations

Variables

This section is empty.

Functions

This section is empty.

Types

type ColumnRows

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

ColumnRows returns schema introspection results as multiple columns. Used for returning table/column metadata to GraphJin.

func NewColumnRows

func NewColumnRows(columns []string, data [][]any) *ColumnRows

NewColumnRows creates rows with multiple columns per row.

func (*ColumnRows) Close

func (r *ColumnRows) Close() error

Close closes the rows.

func (*ColumnRows) Columns

func (r *ColumnRows) Columns() []string

Columns returns column names.

func (*ColumnRows) Next

func (r *ColumnRows) Next(dest []driver.Value) error

Next moves to the next row.

type Conn

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

Conn implements driver.Conn for MongoDB.

func (*Conn) Begin

func (c *Conn) Begin() (driver.Tx, error)

Begin starts a transaction. MongoDB transactions require replica sets.

func (*Conn) BeginTx

func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error)

BeginTx starts a transaction with context.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the connection.

func (*Conn) ExecContext

func (c *Conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error)

ExecContext executes a statement that doesn't return rows.

func (*Conn) Prepare

func (c *Conn) Prepare(query string) (driver.Stmt, error)

Prepare returns a prepared statement.

func (*Conn) QueryContext

func (c *Conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error)

QueryContext executes a query and returns rows.

type Connector

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

Connector implements driver.Connector for MongoDB.

func NewConnector

func NewConnector(client *mongo.Client, database string) *Connector

NewConnector creates a new MongoDB connector that can be used with sql.OpenDB.

func (*Connector) Client

func (c *Connector) Client() *mongo.Client

Client returns the underlying MongoDB client.

func (*Connector) Connect

func (c *Connector) Connect(ctx context.Context) (driver.Conn, error)

Connect returns a connection to the MongoDB database.

func (*Connector) Database

func (c *Connector) Database() string

Database returns the database name.

func (*Connector) Driver

func (c *Connector) Driver() driver.Driver

Driver returns the underlying Driver.

type CursorColumn

type CursorColumn struct {
	Col   string `json:"col"`   // Column name
	Order string `json:"order"` // "asc" or "desc"
}

CursorColumn represents an order-by column for cursor extraction.

type CursorInfo

type CursorInfo struct {
	SelID   int            `json:"sel_id"`   // Selection ID for cursor prefix
	Prefix  string         `json:"prefix"`   // Cursor prefix (e.g., "gj-")
	OrderBy []CursorColumn `json:"order_by"` // Order-by columns for cursor value
}

CursorInfo contains metadata for cursor-based pagination. Used to extract cursor values from query results.

type Driver

type Driver struct{}

Driver implements database/sql/driver.Driver for MongoDB.

func (*Driver) Open

func (d *Driver) Open(name string) (driver.Conn, error)

Open is not supported - use OpenDB with a Connector instead.

type FKConnect

type FKConnect struct {
	Path   string `json:"path"`   // Field path in document (e.g., "owner")
	Column string `json:"column"` // FK column name (e.g., "owner_id")
}

FKConnect represents metadata for FK connect operations. Used to transform owner.connect.id -> owner_id during document processing.

type FieldInfo

type FieldInfo struct {
	Name     string
	BSONType string
	SQLType  string
	Required bool
	IsArray  bool
	IsUnique bool
}

FieldInfo describes a discovered field.

type IntrospectOptions

type IntrospectOptions struct {
	SampleSize        int  `json:"sample_size"`
	IncludeValidators bool `json:"include_validators"`
}

IntrospectOptions configures schema discovery.

type NestedInsert

type NestedInsert struct {
	Collection string         `json:"collection"`
	ID         int            `json:"id"`
	ParentID   int            `json:"parent_id"`
	RelType    string         `json:"rel_type,omitempty"`     // "one_to_one" or "one_to_many"
	FKCol      string         `json:"fk_col,omitempty"`       // FK column name (e.g., "owner_id")
	FKOnParent bool           `json:"fk_on_parent,omitempty"` // true if FK is on parent table, false if on child
	IsConnect  bool           `json:"is_connect,omitempty"`   // true if this is a connect (UPDATE) rather than insert
	Document   map[string]any `json:"document"`
}

NestedInsert represents a single insert in a nested mutation operation.

type NestedUpdate

type NestedUpdate struct {
	Collection string         `json:"collection"`
	ID         int            `json:"id"`
	ParentID   int            `json:"parent_id"`
	Type       string         `json:"type"`                   // "update", "connect", "disconnect"
	RelType    string         `json:"rel_type,omitempty"`     // Relationship type
	FKCol      string         `json:"fk_col,omitempty"`       // FK column to update for connect/disconnect
	FKOnParent bool           `json:"fk_on_parent,omitempty"` // true if FK is on parent table
	Filter     map[string]any `json:"filter"`
	Update     map[string]any `json:"update,omitempty"`
}

NestedUpdate represents a single update in a nested mutation operation.

type QueryCondition

type QueryCondition struct {
	// VarParam is the parameter placeholder (e.g., "$1") for the variable value
	VarParam string `json:"var_param"`
	// Op is the operation: "eq" for @include (show if var == true),
	// "ne" for @skip (show if var != true)
	Op string `json:"op"`
}

QueryCondition represents a condition for variable-based directives. Used for @skip(ifVar: $var) and @include(ifVar: $var) on root selections.

type QueryDSL

type QueryDSL struct {
	Operation         string           `json:"operation"`
	Collection        string           `json:"collection,omitempty"`
	FieldName         string           `json:"field_name,omitempty"`     // GraphQL field name to wrap result in
	Singular          bool             `json:"singular,omitempty"`       // If true, return single object instead of array
	Typename          string           `json:"typename,omitempty"`       // If set, add __typename field with this value to each result
	QueryTypename     string           `json:"query_typename,omitempty"` // If set, add root __typename field with this value
	Pipeline          []map[string]any `json:"pipeline,omitempty"`
	Document          map[string]any   `json:"document,omitempty"`
	Documents         []map[string]any `json:"documents,omitempty"`       // For bulk inserts (insertMany)
	RawDocument       string           `json:"raw_document,omitempty"`    // Raw document placeholder (e.g., "$1")
	ConnectColumn     string           `json:"connect_column,omitempty"`  // Array column to populate from connect
	ConnectPath       string           `json:"connect_path,omitempty"`    // Path to connect IDs in document (e.g., "$2")
	FKConnect         *FKConnect       `json:"fk_connect,omitempty"`      // FK column to populate from connect (single value)
	FKConnects        []FKConnect      `json:"fk_connects,omitempty"`     // Multiple FK columns to populate from connects
	FKValues          map[string]any   `json:"fk_values,omitempty"`       // Direct FK values to set on root document
	ReturnPipeline    []map[string]any `json:"return_pipeline,omitempty"` // Pipeline to run after insert to fetch return data
	Filter            map[string]any   `json:"filter,omitempty"`
	Update            map[string]any   `json:"update,omitempty"`
	Options           map[string]any   `json:"options,omitempty"`
	Presets           map[string]any   `json:"presets,omitempty"` // Preset values to merge with document
	Params            []string         `json:"params,omitempty"`
	Queries           []*QueryDSL      `json:"queries,omitempty"`             // For multi_aggregate operations
	Inserts           []NestedInsert   `json:"inserts,omitempty"`             // For nested_insert operations
	Updates           []NestedUpdate   `json:"updates,omitempty"`             // For nested_update operations
	RootCollection    string           `json:"root_collection,omitempty"`     // Root collection for nested_insert/nested_update
	RootMutateID      int              `json:"root_mutate_id,omitempty"`      // ID of root mutation for nested_insert
	AllSameCollection bool             `json:"all_same_collection,omitempty"` // True if all inserts are in same collection (recursive-only)
	Condition         *QueryCondition  `json:"condition,omitempty"`           // Condition for variable-based directives
	CursorInfo        *CursorInfo      `json:"cursor_info,omitempty"`         // Cursor pagination metadata
	CursorParam       string           `json:"cursor_param,omitempty"`        // Parameter placeholder for cursor value (e.g., "$1")
}

QueryDSL represents the JSON query structure generated by the MongoDB dialect. This is the "SQL" that GraphJin generates for MongoDB.

func ParseQuery

func ParseQuery(query string) (*QueryDSL, error)

ParseQuery parses a JSON query DSL string into a QueryDSL struct.

func (*QueryDSL) SubstituteParams

func (q *QueryDSL) SubstituteParams(args []any) error

SubstituteParams replaces parameter placeholders ($1, $2, etc.) with actual values.

type Result

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

Result implements driver.Result.

func (*Result) InsertedID

func (r *Result) InsertedID() string

InsertedID returns the inserted document ID as a string.

func (*Result) LastInsertId

func (r *Result) LastInsertId() (int64, error)

LastInsertId returns the ID of the last inserted document.

func (*Result) RowsAffected

func (r *Result) RowsAffected() (int64, error)

RowsAffected returns the number of affected rows.

type Rows

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

Rows implements driver.Rows for MongoDB query results.

func NewRows

func NewRows(cursor *mongo.Cursor, columns []string) *Rows

NewRows creates a new Rows from a MongoDB cursor.

func (*Rows) Close

func (r *Rows) Close() error

Close closes the rows iterator.

func (*Rows) Columns

func (r *Rows) Columns() []string

Columns returns the column names.

func (*Rows) Next

func (r *Rows) Next(dest []driver.Value) error

Next moves to the next row. For GraphJin, we return the entire document as JSON in a single column.

type SingleValueRows

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

SingleValueRows returns a single row with a single JSON value. Used for aggregate results that need to be wrapped.

func NewSingleValueRows

func NewSingleValueRows(value []byte, columns []string) *SingleValueRows

NewSingleValueRows creates rows that return a single JSON value.

func (*SingleValueRows) Close

func (r *SingleValueRows) Close() error

Close closes the rows.

func (*SingleValueRows) Columns

func (r *SingleValueRows) Columns() []string

Columns returns column names.

func (*SingleValueRows) Next

func (r *SingleValueRows) Next(dest []driver.Value) error

Next returns the single value.

type Stmt

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

Stmt implements driver.Stmt for MongoDB.

func (*Stmt) Close

func (s *Stmt) Close() error

Close closes the statement.

func (*Stmt) Exec

func (s *Stmt) Exec(args []driver.Value) (driver.Result, error)

Exec executes a query that doesn't return rows.

func (*Stmt) NumInput

func (s *Stmt) NumInput() int

NumInput returns the number of placeholder parameters.

func (*Stmt) Query

func (s *Stmt) Query(args []driver.Value) (driver.Rows, error)

Query executes a query that returns rows.

type Tx

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

Tx implements driver.Tx for MongoDB transactions.

func (*Tx) Commit

func (t *Tx) Commit() error

Commit commits the transaction.

func (*Tx) Rollback

func (t *Tx) Rollback() error

Rollback aborts the transaction.

Jump to

Keyboard shortcuts

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