fs

package
v1.11.2 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FileNameForObject added in v1.5.1

func FileNameForObject(objectName string) string

FileNameForObject returns a string containing the filename to use for the SQLFile representing the supplied object name. Special characters in the objectName will be removed; however, there is no risk of "conflicts" since a single SQLFile can store definitions for multiple objects.

func HostDefaultDirName

func HostDefaultDirName(hostname string, port int) string

HostDefaultDirName returns a default relative directory name to use for the supplied instance host and port. Intended for use in situations where a user can optionally supply an arbitrary name, but they have not done so.

func MakeTestDirectory

func MakeTestDirectory(t *testing.T, path string)

MakeTestDirectory wraps os.MkdirAll. If an error occurs, it is fatal to the test.

func ParentOptionFiles

func ParentOptionFiles(dirPath string, baseConfig *mybase.Config) ([]*mybase.File, string, error)

ParentOptionFiles returns a slice of *mybase.File, corresponding to the option files in the specified path's parent dir hierarchy. Evaluation of parent dirs stops once we hit either a directory containing .git, the user's home directory, or the root of the filesystem. The result is ordered such that the closest-to-root dir's File is returned first and this dir's direct parent File last. The return value excludes dirPath's file, as well as the home directory's, as these are presumed to be parsed elsewhere. The files will be read and parsed, using baseConfig to know which options are defined and valid. An absolute path to the "repo base" is also returned as a string. This will typically be either a dir containing a .git subdir, or the rootmost dir containing a .skeema file; failing that, it will be the supplied dirPath.

func ReadTestFile

func ReadTestFile(t *testing.T, filename string) string

ReadTestFile wraps os.ReadFile. If an error occurs, it is fatal to the test.

func RemoveTestDirectory

func RemoveTestDirectory(t *testing.T, path string)

RemoveTestDirectory wraps os.RemoveAll. If an error occurs, it is fatal to the test.

func RemoveTestFile

func RemoveTestFile(t *testing.T, filename string)

RemoveTestFile deletes a file (or directory). If an error occurs, it is fatal to the test.

func WriteTestFile

func WriteTestFile(t *testing.T, filename, contents string)

WriteTestFile wraps os.WriteFile. If an error occurs, it is fatal to the test.

Types

type ConfigError added in v1.9.0

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

ConfigError indicates a misconfiguration in the directory's .skeema file or the command-line overrides.

func ConfigErrorf added in v1.9.0

func ConfigErrorf(format string, a ...any) ConfigError

ConfigErrorf formats and returns a new ConfigError value.

func (ConfigError) Error added in v1.9.0

func (ce ConfigError) Error() string

Error satisfies the builtin error interface.

func (ConfigError) ExitCode added in v1.9.0

func (ce ConfigError) ExitCode() int

ExitCode returns 78 for ConfigError, corresponding to EX_CONFIG in BSD's SYSEXITS(3) manpage.

func (ConfigError) Unwrap added in v1.9.0

func (ce ConfigError) Unwrap() error

Unwrap satisfies Golang errors package unwrapping behavior.

type Dir

type Dir struct {
	Path                  string
	Config                *mybase.Config
	OptionFile            *mybase.File
	SQLFiles              map[string]*SQLFile   // .sql files, keyed by absolute file path, usually with file name lowercased
	UnparsedStatements    []*tengo.Statement    // statements with unknown type / not supported by this package
	NamedSchemaStatements []*tengo.Statement    // statements with explicit schema names: USE command or CREATEs with schema name qualifier
	LogicalSchemas        []*LogicalSchema      // for now, always 0 or 1 elements; 2+ in same dir to be supported in future
	IgnorePatterns        []tengo.ObjectPattern // regexes for matching objects that should be ignored
	ParseError            error                 // any fatal error found parsing dir's config or contents
	// contains filtered or unexported fields
}

Dir is a parsed representation of a directory that may have contained a .skeema config file and/or *.sql files.

func ParseDir

func ParseDir(dirPath string, globalConfig *mybase.Config) (*Dir, error)

ParseDir parses the specified directory, including all *.sql files in it, its .skeema config file, and all .skeema config files of its parent directory hierarchy. Evaluation of parent dirs stops once we hit either a directory containing .git, the user's home directory, or the root of the filesystem. Config sources are ordered such that the closest-to-root-dir's .skeema file is added first (and the current working dir's last), meaning that options "cascade" down the fs hierarchy and can be overridden by child directories.

func (*Dir) BaseName

func (dir *Dir) BaseName() string

BaseName returns the name of the directory without the rest of its path.

func (*Dir) CreateOptionFile

func (dir *Dir) CreateOptionFile(optionFile *mybase.File) (err error)

CreateOptionFile adds the supplied option file to dir. It is an error if dir already has an option file.

func (*Dir) Delete

func (dir *Dir) Delete() error

Delete unlinks the directory and all files within.

func (*Dir) DirtyFiles added in v1.10.0

func (dir *Dir) DirtyFiles() (result []*SQLFile)

DirtyFiles returns a slice of SQLFiles that have been marked as dirty.

func (*Dir) FileFor added in v1.10.0

func (dir *Dir) FileFor(keyer tengo.ObjectKeyer) *SQLFile

FileFor returns a SQLFile associated with the supplied keyer. If keyer is a *tengo.Statement with non-empty File field, that path will be used as-is. Otherwise, FileFor returns the default location for the supplied keyer based on its type and name. In either case, if no known SQLFile exists at that location yet, FileFor will instantiate a new SQLFile value for it, but no underlying filesystem file is created/written by this method.

func (*Dir) FirstInstance

func (dir *Dir) FirstInstance() (*tengo.Instance, error)

FirstInstance returns at most one tengo.Instance based on the directory's configuration. If the config maps to multiple instances, only the first will be returned. If the config maps to no instances, nil will be returned. The instance WILL be checked for connectivity. If multiple instances are returned and some have connectivity issues, the first reachable instance will be returned.

func (*Dir) Generator

func (dir *Dir) Generator() (major, minor, patch int, edition string)

Generator returns the version and edition of Skeema used to init or most most recently pull this dir's contents. If this cannot be determined, all results will be zero values.

func (*Dir) HasFile

func (dir *Dir) HasFile(name string) (bool, error)

HasFile returns true if the specified filename exists in dir.

func (*Dir) HasSchema

func (dir *Dir) HasSchema() bool

HasSchema returns true if this dir maps to at least one schema, either by stating a "schema" option in this dir's option file for the current environment, and/or by having *.sql files that explicitly mention a schema name.

func (*Dir) Hostnames

func (dir *Dir) Hostnames() ([]string, error)

Hostnames returns 0 or more hosts that the directory maps to. This properly handles the host option being set to a comma-separated list of multiple hosts, or the host-wrapper option being used to shell out to an external script to obtain hosts.

func (*Dir) InstanceDefaultParams

func (dir *Dir) InstanceDefaultParams() (string, error)

InstanceDefaultParams returns a param string for use in constructing a DSN. Any overrides specified in the config for this dir will be taken into account. The returned string will already be in the correct format (HTTP query string). An error will be returned if the configuration tried manipulating params that should not be user-specified. Note that these vars are used as the *default* params for an Instance, but individual callsites can still override things as needed. For example, Tengo will automatically manipulate a few params whenever querying information_schema or running SHOW CREATE.

func (*Dir) Instances

func (dir *Dir) Instances() ([]*tengo.Instance, error)

Instances returns 0 or more tengo.Instance pointers, based on the directory's configuration. The Instances will NOT be checked for connectivity. However, if the configuration is invalid (for example, illegal hostname or invalid connect-options), an error will be returned instead of any instances.

func (*Dir) Password added in v1.9.0

func (dir *Dir) Password(hosts ...string) (string, error)

Password returns the configured password in this dir, a cached password from a previous interactive password check, or an interactively-prompted password from STDIN if one should be obtained based on the directory's configuration. If interactive input is requested and successful, the password will be returned and also cached, so that subsequent identical requests return the password without prompting.

Optionally supply one or more hostnames to affect the behavior of interactive password prompts and caching: with no hosts, the prompt text will mention the directory and be cached in the directory's configuration; with one or more hosts, the prompt text will mention the first host and will cache values in a package-level map independent of this dir.

An error is returned if a password should be prompted but cannot, for example due to STDIN not being a TTY.

func (*Dir) Port added in v1.9.0

func (dir *Dir) Port() (int, bool)

Port returns the port number in the directory's configuration (often the default of 3306) and a boolean indicating whether the port was configured explicitly using the port option.

func (*Dir) RelPath

func (dir *Dir) RelPath() string

RelPath attempts to return the directory path relative to the dir's repoBase. If this cannot be determined, the BaseName is returned. This method is intended for situations when the dir's location within its repo is more relevant than the dir's absolute path.

func (*Dir) SchemaNames

func (dir *Dir) SchemaNames(instance *tengo.Instance) (names []string, err error)

SchemaNames interprets the value of the dir's "schema" option, returning one or more schema names that the statements in dir's *.sql files will be applied to, in cases where no schema name is explicitly specified in SQL statements. If the ignore-schema option is set, it will filter out matching results from the returned slice. An instance must be supplied since the value may be instance-specific.

func (*Dir) ShouldIgnore added in v1.9.0

func (dir *Dir) ShouldIgnore(object tengo.ObjectKeyer) bool

ShouldIgnore returns true if the directory's configuration states that the supplied object/key/statement should be ignored.

func (*Dir) String

func (dir *Dir) String() string

func (*Dir) Subdir added in v1.10.0

func (dir *Dir) Subdir(name string) (*Dir, error)

Subdir returns a specific subdirectory of dir by name. If the named subdirectory does not exist or is a non-directory, then a nil *Dir will be returned alongside an error. In some other error conditions (such as a problem parsing the directory's .skeema file or *.sql files), a non-nil *Dir may be returned even alongside a non-nil error.

func (*Dir) Subdirs

func (dir *Dir) Subdirs() ([]*Dir, error)

Subdirs reads the list of direct, non-hidden subdirectories of dir, parses them (*.sql and .skeema files), and returns them. An error will be returned if there are problems reading dir's the directory list. Otherwise, err is nil, but some of the returned Dir values will have a non-nil ParseError if any problems were encountered in that subdir.

func (*Dir) ValidateInstance

func (dir *Dir) ValidateInstance(instance *tengo.Instance) error

ValidateInstance confirms the supplied instance is (or has been) reachable, and applies any dir-configured Flavor override if the instance's flavor cannot be auto-detected. An error will be returned if the instance is not reachable. Otherwise, the return value will be nil, but any flavor mismatches/problems will be logged.

type DuplicateDefinitionError

type DuplicateDefinitionError struct {
	ObjectKey tengo.ObjectKey
	FirstFile string
	FirstLine int
	DupeFile  string
	DupeLine  int
}

DuplicateDefinitionError is an error returned when Dir.parseContents() encounters multiple CREATE statements for the same exact object.

func (DuplicateDefinitionError) Error

func (dde DuplicateDefinitionError) Error() string

Error satisfies the builtin error interface.

type LogicalSchema

type LogicalSchema struct {
	Name      string
	CharSet   string
	Collation string
	Creates   map[tengo.ObjectKey]*tengo.Statement
	Alters    []*tengo.Statement // Alterations that are run after the Creates
}

LogicalSchema represents a set of statements from *.sql files in a directory that all operated on the same schema. Note that Name is often blank, which means "all SQL statements in this dir that don't have an explicit USE statement before them". This "nameless" LogicalSchema is mapped to schema names based on the "schema" option in the dir's OptionFile.

func NewLogicalSchema added in v1.10.0

func NewLogicalSchema() *LogicalSchema

NewLogicalSchema returns a pointer to an empty, nameless LogicalSchema. Any map fields will be properly initialized; all other fields will be left at zero values.

func (*LogicalSchema) AddStatement

func (logicalSchema *LogicalSchema) AddStatement(stmt *tengo.Statement) error

AddStatement adds the supplied statement into the appropriate data structure within the receiver. This is useful when assembling a new logical schema. An error will be returned if a duplicate CREATE object name/type pair is added.

func (*LogicalSchema) Empty added in v1.10.0

func (logicalSchema *LogicalSchema) Empty() bool

Empty returns true if the LogicalSchema contains no statements.

func (*LogicalSchema) LowerCaseNames added in v1.8.0

func (logicalSchema *LogicalSchema) LowerCaseNames(mode tengo.NameCaseMode) error

LowerCaseNames adjusts logicalSchema in-place such that its object names are forced to lower-case as appropriate for the supplied NameCaseMode. An error will be returned if case-insensitivity would result in duplicate objects with the same name and type.

type SQLFile

type SQLFile struct {
	FilePath   string
	Statements []*tengo.Statement
	Dirty      bool
}

SQLFile represents a file containing SQL statements.

func (*SQLFile) AddStatement added in v1.10.0

func (sqlFile *SQLFile) AddStatement(stmt *tengo.Statement)

AddStatement appends stmt to sqlFile's list of statements. This method marks the file as dirty, but does not rewrite the file. This method may adjust stmt.Text and stmt.Delimiter as needed to ensure the text contains the appropriate delimiter for the type of statement, as well as a trailing newline. DELIMITER command statements may also be inserted into sqlFile as necessary for stmt.

func (*SQLFile) Delete

func (sqlFile *SQLFile) Delete() error

Delete unlinks the file.

func (*SQLFile) EditStatementText added in v1.10.0

func (sqlFile *SQLFile) EditStatementText(stmt *tengo.Statement, newText string, compound bool)

EditStatementText sets stmt.Text to a new value consisting of newText plus an appropriate delimiter and newline. It marks the file as dirty, and (if needed for a compound statement) adds DELIMITER commands around stmt in the file's list of statements. The supplied newText should NOT have a delimiter or trailing newline. This method panics if stmt's address is not actually found among the file's statement pointers slice.

func (*SQLFile) Exists

func (sqlFile *SQLFile) Exists() (bool, error)

Exists returns true if sqlFile already exists in the filesystem, false if not.

func (*SQLFile) FileName

func (sqlFile *SQLFile) FileName() string

FileName returns the file name of sqlFile without its directory path.

func (*SQLFile) RemoveStatement added in v1.10.0

func (sqlFile *SQLFile) RemoveStatement(stmt *tengo.Statement)

RemoveStatement removes stmt from the file's in-memory list of statements, and marks the file as dirty. Panics if the address of stmt is not actually found in its expected file's in-memory representation.

func (*SQLFile) Write added in v1.10.0

func (sqlFile *SQLFile) Write() (n int, err error)

Write creates or replaces the SQLFile with the current statements, returning the number of bytes written. If the file's statements now only consist of comments, whitespace, and commands (e.g. USE, DELIMITER) then the file will be deleted instead, and a length of 0 will be returned. The file will be unmarked as dirty if the operation was successful.

Jump to

Keyboard shortcuts

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