### Count Matching Records Source: https://context7.com/genieframework/searchlight.jl/llms.txt Use `count` to get the total number of records or the number of records matching specific criteria. ```julia total = count(User) # => Int ``` ```julia active_count = count(User, active = true) # => Int ``` -------------------------------- ### Retrieve First or Last Record Source: https://context7.com/genieframework/searchlight.jl/llms.txt Use `first` and `last` to get the first or last record based on default or custom ordering. Returns nothing if no records are found. ```julia first_user = first(User) # => User with lowest id, or nothing ``` ```julia last_article = last(Article) # => Article with highest id (default DESC order), or nothing ``` ```julia # Custom order first_alpha = first(User, order = SQLOrder(:username, :asc)) ``` -------------------------------- ### model_file_name Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/generator.md Gets the file name for a model. ```APIDOC ## model_file_name ### Description Gets the file name for a model. ### Method ```julia model_file_name(name::String) ``` ``` -------------------------------- ### validator_file_name Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/generator.md Gets the file name for a validator. ```APIDOC ## validator_file_name ### Description Gets the file name for a validator. ### Method ```julia validator_file_name(name::String) ``` ``` -------------------------------- ### setup_resource_path Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/generator.md Sets up the resource path. ```APIDOC ## setup_resource_path ### Description Sets up the resource path. ### Method ```julia setup_resource_path(path::String) ``` ``` -------------------------------- ### SearchLight.connect Source: https://context7.com/genieframework/searchlight.jl/llms.txt Establishes the database connection. This function is implemented by the adapter package and can accept a `Dict` of connection parameters or read from loaded configuration. ```APIDOC ## `SearchLight.connect` — Connect to the database Establishes the database connection. Implemented by the adapter package; takes a `Dict` or reads from loaded config. ```julia using SearchLight, SearchLightSQLite # Connect directly with a Dict conn = SearchLight.connect(Dict("database" => "db/app.sqlite", "adapter" => "SQLite")) # Or connect after loading config file SearchLight.Configuration.load("db/connection.yml"; context = @__MODULE__) SearchLight.connect(SearchLight.config.db_config_settings) ``` ``` -------------------------------- ### Framework Initialization Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/migrations.md Function to initialize the migration system. ```APIDOC ## Framework Initialization ### `init()` Initializes the migration system, ensuring the migrations table exists. ``` -------------------------------- ### Connect to the Database Source: https://context7.com/genieframework/searchlight.jl/llms.txt Establishes a database connection using provided settings or loaded configuration. The connection logic is implemented by specific adapter packages. ```julia using SearchLight, SearchLightSQLite # Connect directly with a Dict conn = SearchLight.connect(Dict("database" => "db/app.sqlite", "adapter" => "SQLite")) # Or connect after loading config file SearchLight.Configuration.load("db/connection.yml"; context = @__MODULE__) SearchLight.connect(SearchLight.config.db_config_settings) ``` -------------------------------- ### Get Primary Key Field Name Source: https://context7.com/genieframework/searchlight.jl/llms.txt Retrieves the name of the primary key field for a given SearchLight model. This is crucial for model identification. ```julia SearchLight.pk(User) # => "id" ``` -------------------------------- ### Manage Database Migrations Source: https://context7.com/genieframework/searchlight.jl/llms.txt Run individual or all migrations using `Migration.up`, `Migration.down`, `Migration.all_up!!`, and `Migration.all_down!!`. Also includes functions to initialize the schema, check status, and manage individual migrations. ```julia # A migration file looks like: module CreateTableArticles import SearchLight.Migrations: create_table, column, primary_key, add_index, drop_table function up() create_table(:articles) do [ primary_key() column(:title, :string, limit = 255) column(:body, :text) column(:user_id, :int) column(:active, :bool, default = true) ] end add_index(:articles, :user_id) add_index(:articles, :title) end function down() drop_table(:articles) end end # Run migrations programmatically Migration.create_migrations_table() # initialize schema_migrations table Migration.all_up!!() # run all pending migrations up Migration.status() # print migration status table Migration.last_up() # run last migration up Migration.last_down() # roll back last migration Migration.up("CreateTableArticles") # run specific migration up Migration.down("CreateTableArticles") # roll back specific migration ``` -------------------------------- ### Get DB Table Name for Model Source: https://context7.com/genieframework/searchlight.jl/llms.txt Retrieves the database table name associated with a given SearchLight model. Ensure the model is defined before calling. ```julia SearchLight.table(User) # => "users" SearchLight.table(Article) # => "articles" ``` -------------------------------- ### newconfig Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/generator.md Creates a new configuration file. ```APIDOC ## newconfig ### Description Creates a new configuration file. ### Method ```julia newconfig(name::String) ``` ``` -------------------------------- ### Migration.up / Migration.down / Migration.all_up!! Source: https://context7.com/genieframework/searchlight.jl/llms.txt Provides functions to run, roll back, and manage individual or all database migrations. ```APIDOC ### `Migration.up` / `Migration.down` / `Migration.all_up!!` / `Migration.all_down!!` Run individual or all migrations. ### Example Migration File Structure ```julia module CreateTableArticles import SearchLight.Migrations: create_table, column, primary_key, add_index, drop_table function up() create_table(:articles) do [ primary_key() column(:title, :string, limit = 255) column(:body, :text) column(:user_id, :int) column(:active, :bool, default = true) ] end add_index(:articles, :user_id) add_index(:articles, :title) end function down() drop_table(:articles) end end ``` ### Usage ```julia # Run migrations programmatically Migration.create_migrations_table() # initialize schema_migrations table Migration.all_up!!() # run all pending migrations up Migration.status() # print migration status table Migration.last_up() # run last migration up Migration.last_down() # roll back last migration Migration.up("CreateTableArticles") # run specific migration up Migration.down("CreateTableArticles") # roll back specific migration ``` ``` -------------------------------- ### begin_transaction Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/transactions.md Initiates a new database transaction. ```APIDOC ## begin_transaction ### Description Initiates a new database transaction. ### Method `begin_transaction()` ### Parameters None ### Response Returns a transaction object representing the new transaction. ``` -------------------------------- ### Retrieve Records with SQLQuery Source: https://context7.com/genieframework/searchlight.jl/llms.txt Use SQLQuery to build complex queries with WHERE, LIMIT, and ORDER clauses. Inspect the generated SQL using SearchLight.sql. ```julia q = SQLQuery(where = [SQLWhereExpression("active = ?", true)], limit = 5) active_subset = all(User, q) ``` ```julia q = SQLQuery( columns = [SQLColumn("username"), SQLColumn("email")], where = [ SQLWhereExpression("active = ?", true), SQLWhereExpression("OR age > ?", 18) ], order = [SQLOrder(:username, :asc), SQLOrder(:age, :desc)], group = [SQLColumn(:age)], having = [SQLWhereExpression("COUNT(*) > ?", 1)], limit = SQLLimit(50), offset = 100 ) users = find(User, q) # Inspect the generated SQL println(SearchLight.sql(User, q)) # => SELECT "users"."username" AS "users_username", ... FROM "users" WHERE ... ``` -------------------------------- ### Access Global Configuration Settings Source: https://context7.com/genieframework/searchlight.jl/llms.txt Accesses various application-level configuration settings for SearchLight. These settings control environment, logging, and database behavior. ```julia SearchLight.config.app_env # => "dev" | "prod" | "test" SearchLight.config.db_migrations_folder # => "db/migrations" SearchLight.config.db_migrations_table_name # => "schema_migrations" SearchLight.config.log_queries # => true SearchLight.config.log_level # => Logging.Debug SearchLight.config.log_to_file # => true ``` -------------------------------- ### Configuration.load Source: https://context7.com/genieframework/searchlight.jl/llms.txt Loads database configuration from a YAML file (e.g., connection.yml) and returns the settings for the current environment. It can optionally accept a context module to automatically import the appropriate adapter. ```APIDOC ## `Configuration.load` — Load database configuration from YAML Reads a `connection.yml` file and returns the settings for the current environment. Optionally accepts a `context` module to automatically `using` the appropriate adapter. ```julia # db/connection.yml # env: dev # # dev: # adapter: SQLite # database: db/app.sqlite # # prod: # adapter: PostgreSQL # host: localhost # port: 5432 # database: myapp # username: pguser # password: secret # config: # log_queries: true # log_level: :info using SearchLight # Load config and auto-import the adapter conn_info = SearchLight.Configuration.load("db/connection.yml"; context = @__MODULE__) # => Dict{String,Any}("adapter" => "SQLite", "database" => "db/app.sqlite", ...) ``` ``` -------------------------------- ### Load Database Configuration from YAML Source: https://context7.com/genieframework/searchlight.jl/llms.txt Loads database connection settings from a YAML file for the current environment. Optionally uses a context module to automatically import the correct adapter. ```julia using SearchLight # Load config and auto-import the adapter conn_info = SearchLight.Configuration.load("db/connection.yml"; context = @__MODULE__) # => Dict{String,Any}("adapter" => "SQLite", "database" => "db/app.sqlite", ...) ``` -------------------------------- ### Generate New Migration Files Source: https://context7.com/genieframework/searchlight.jl/llms.txt Create new migration files for database schema changes. `Migration.new_table` generates a file for creating a new table, while `Migration.new` creates a blank migration file. ```julia using SearchLight.Migration # Generate a new table migration file Migration.new_table("create_table_articles", "articles") # => creates db/migrations/20240101120000_create_table_articles.jl # Generate a blank migration Migration.new("add_index_to_users_email") ``` -------------------------------- ### newresource Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/generator.md Creates a new resource definition. ```APIDOC ## newresource ### Description Creates a new resource definition. ### Method ```julia newresource(name::String) ``` ``` -------------------------------- ### newconfig Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/filetemplates.md Generates a new configuration file. ```APIDOC ## newconfig ### Description Generates a new configuration file. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### Build and Populate Model with `createwith` Source: https://context7.com/genieframework/searchlight.jl/llms.txt Use `createwith` to build and populate a new model instance from a Dict. The model is not saved automatically. ```julia user = createwith(User, Dict("username" => "dave", "email" => "dave@example.com", "age" => 22)) save!(user) ``` -------------------------------- ### adapter_default_config Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/filetemplates.md Provides the default configuration for an adapter. ```APIDOC ## adapter_default_config ### Description Provides the default configuration for an adapter. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### newmigration Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/filetemplates.md Generates a new generic migration file. ```APIDOC ## newmigration ### Description Generates a new generic migration file. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### Migration.new_table / Migration.new Source: https://context7.com/genieframework/searchlight.jl/llms.txt Generates new migration files for creating tables or for custom schema changes. ```APIDOC ### `Migration.new_table` / `Migration.new` — Create migration files Generates new migration files for creating tables or for custom schema changes. ### Usage ```julia using SearchLight.Migration # Generate a new table migration file Migration.new_table("create_table_articles", "articles") # => creates db/migrations/20240101120000_create_table_articles.jl # Generate a blank migration Migration.new("add_index_to_users_email") ``` ``` -------------------------------- ### newmodel Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/filetemplates.md Generates a new model file. ```APIDOC ## newmodel ### Description Generates a new model file. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### SQLJoin Source: https://context7.com/genieframework/searchlight.jl/llms.txt Defines how to perform JOIN queries by specifying related tables, join conditions, and desired columns. ```APIDOC ## SQLJoin — JOIN queries Defines how to perform JOIN queries by specifying related tables, join conditions, and desired columns. ### Usage ```julia # Fetch Articles with their author User data joins = [ SQLJoin(User, SQLOn("articles.user_id", "users.id"), join_type = SQLJoinType("LEFT"), columns = [SQLColumn("users.username AS author_name")]) ] q = SQLQuery(where = [SQLWhereExpression("articles.active = ?", true)]) articles = find(Article, q, joins) ``` ``` -------------------------------- ### Persist and Return Model with `save!` / `save!!` Source: https://context7.com/genieframework/searchlight.jl/llms.txt Use `save!` or `save!!` to persist a model, reload it from the DB with its new ID, and return it. Throws an error on failure. ```julia user = User(username = "carol", email = "carol@example.com", age = 28) # save! returns the persisted model with id populated user = save!(user) println(user.id) # => 42 (assigned by DB) ``` ```julia # Use the bang form in a pipeline article = Article(title = "Hello", body = "World", user_id = user.id.value) |> save! ``` -------------------------------- ### Scaffold New Resources with SearchLight.jl Generator Source: https://context7.com/genieframework/searchlight.jl/llms.txt Use `Generator.newresource` to scaffold model, validator, test, and migration files for a new resource, or `Generator.newmodel` to generate only the model file. ```julia using SearchLight.Generator # Generate a model + migration + validator + test files Generator.newresource("Article") # Creates: # app/resources/articles/Articles.jl # app/resources/articles/ArticlesValidator.jl # test/articles_test.jl # db/migrations/_create_table_articles.jl # Generate model file only Generator.newmodel("Comment") ``` -------------------------------- ### Table and Column Definitions Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/migrations.md Functions for defining tables, columns, and indexes within migrations. ```APIDOC ## Table and Column Definitions ### `create_table(name::Symbol, block::Function)` Creates a new table with the specified name and applies column definitions within the block. ### `column(name::Symbol, type::DataType, options::Dict)` Defines a column with a name, type, and optional properties. ### `columns(cols::Vector)` Defines multiple columns. ### `column_id(name::Symbol=:id, options::Dict=Dict())` Defines an auto-incrementing primary key column. ### `add_index(table_name::Symbol, column_names::Union{Symbol, Vector{Symbol}}, options::Dict=Dict())` Adds an index to a table on specified columns. ### `add_indexes(table_name::Symbol, indexes::Dict)` Adds multiple indexes to a table. ### `add_column(table_name::Symbol, column_name::Symbol, column_type::DataType, options::Dict=Dict())` Adds a new column to an existing table. ### `add_columns(table_name::Symbol, columns::Dict)` Adds multiple columns to an existing table. ### `drop_table(table_name::Symbol, options::Dict=Dict())` Drops a table. ### `remove_column(table_name::Symbol, column_name::Symbol, options::Dict=Dict())` Removes a column from a table. ### `remove_columns(table_name::Symbol, column_names::Vector{Symbol}, options::Dict=Dict())` Removes multiple columns from a table. ### `remove_index(table_name::Symbol, index_name::Symbol, options::Dict=Dict())` Removes an index from a table. ### `remove_indexes(table_name::Symbol, index_names::Vector{Symbol}, options::Dict=Dict())` Removes multiple indexes from a table. ### `remove_indices(table_name::Symbol, index_names::Vector{Symbol}, options::Dict=Dict())` Alias for `remove_indexes`. ``` -------------------------------- ### Generate Default Connection Config Source: https://context7.com/genieframework/searchlight.jl/llms.txt Generates a default connection.yml file for database configuration. This file is essential for setting up database connections. ```julia Generator.newconfig() ``` -------------------------------- ### Migration Table Initialization Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/migrations.md Function to initialize the migrations table in the database. ```APIDOC ## Migration Table Initialization ### `create_migrations_table()` Creates the table used to store migration status if it does not already exist. ``` -------------------------------- ### newmigration Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/generator.md Creates a new migration. ```APIDOC ## newmigration ### Description Creates a new migration. ### Method ```julia newmigration(name::String) ``` ``` -------------------------------- ### Delete Records with `delete` / `deleteall` Source: https://context7.com/genieframework/searchlight.jl/llms.txt Use `delete` to remove a specific record and `deleteall` to remove all records from a table. ```julia user = findone(User, id = 5) SearchLight.delete(user) # deletes the single record ``` ```julia SearchLight.deleteall(User) # deletes ALL rows in the users table ``` -------------------------------- ### QueryBuilder DSL for Composable Queries Source: https://context7.com/genieframework/searchlight.jl/llms.txt Build SQL queries using a chainable DSL with the `+` operator. Supports `from`, `select`, `where`, `order`, `limit`, `offset`, `group`, `having`, and `prepare`. ```julia using SearchLight.QueryBuilder # Compose query parts with + qp = from(User) + where("active = ?", true) + order(:username) + limit(10) + offset(0) users = find(User, qp) # Select specific columns qp2 = from(User) + select(:username, :email) + where("age >= ?", 18) + order(:age, :desc) users2 = find(User, qp2) # Reuse a base query and extend it base = where("active = ?", true) + order(:username) page1 = find(User, from(User) + base + limit(20) + offset(0)) page2 = find(User, from(User) + base + limit(20) + offset(20)) # Inspect SQL println(SearchLight.sql(User, from(User) + where("age > ?", 30))) ``` -------------------------------- ### all Source: https://context7.com/genieframework/searchlight.jl/llms.txt Retrieves all records for a given model, with optional parameters for ordering, limiting the number of results, and setting an offset for pagination. It can also fetch specific columns. ```APIDOC ## `all` — Retrieve all records Returns all rows for a model with optional ordering, limit, and offset. ```julia # All records all_users = all(User) # With pagination page_2 = all(User, limit = 20, offset = 20, order = SQLOrder(:username)) # Specific columns only cols = all(User, columns = [SQLColumn(:id), SQLColumn(:username)]) ``` ``` -------------------------------- ### Migration Creation and Naming Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/migrations.md Functions for creating new migrations and deriving naming conventions. ```APIDOC ## Migration Creation and Naming ### `new_table(name::Symbol)` Creates a new table definition for a migration. ### `newtable(name::Symbol)` Alias for `new_table`. ### `relationship_table_name(name1::Symbol, name2::Symbol)` Derives the conventional name for a relationship table between two entities. ### `new(name::String)` Creates a new migration file with the given name. ``` -------------------------------- ### Migration Execution Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/migrations.md Functions for running migrations up or down, and for storing migration status. ```APIDOC ## Migration Execution ### `run_migration(migration::DatabaseMigration, direction::Symbol)` Runs a specific migration in the given direction (:up or :down). ### `store_migration_status(migration::DatabaseMigration, status::Symbol)` Stores the status of a migration. ### `up(migration::DatabaseMigration)` Applies a migration upwards. ### `up_by_module_name(name::Symbol)` Applies the migration corresponding to the given module name upwards. ### `down(migration::DatabaseMigration)` Reverts a migration downwards. ### `down_by_module_name(name::Symbol)` Reverts the migration corresponding to the given module name downwards. ### `migration_by_module_name(name::Symbol)` Retrieves a migration by its module name. ### `all_down!()` Reverts all applied migrations downwards. ### `all_up!()` Applies all pending migrations upwards. ``` -------------------------------- ### Configuration Settings Source: https://context7.com/genieframework/searchlight.jl/llms.txt Access and modify application-level configuration settings. ```APIDOC ## Configuration Settings ### `Configuration.Settings` — App-level configuration object Provides access to global configuration parameters. ```julia # Access the global config object SearchLight.config.app_env # => "dev" | "prod" | "test" SearchLight.config.db_migrations_folder # => "db/migrations" SearchLight.config.db_migrations_table_name # => "schema_migrations" SearchLight.config.log_queries # => true SearchLight.config.log_level # => Logging.Debug SearchLight.config.log_to_file # => true # Environment is read from ENV["SEARCHLIGHT_ENV"] or the connection.yml `env` key # Override programmatically: ENV["SEARCHLIGHT_ENV"] = "prod" # Or set via connection.yml: # env: prod # # prod: # adapter: PostgreSQL # host: db.example.com # ... # config: # log_queries: false # log_level: :warn ``` ``` -------------------------------- ### Model Conversion and Query Building Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/searchlight.md Functions for converting data to models and building SQL queries programmatically. ```APIDOC ## to_models ### Description Converts a collection of database rows into a collection of model instances. ### Method `to_models(rows, model_type) ### Parameters - `rows`: The database rows to convert. - `model_type`: The type of model to convert to. ### Response Returns a collection of model instances. ``` ```APIDOC ## to_model ### Description Converts a single database row into a model instance. ### Method `to_model(row, model_type) ### Parameters - `row`: The database row to convert. - `model_type`: The type of model to convert to. ### Response Returns a model instance. ``` ```APIDOC ## to_select_part ### Description Builds the SELECT part of an SQL query. ### Method `to_select_part(columns) ### Parameters - `columns`: The columns to select. ### Response Returns the SQL string for the SELECT clause. ``` ```APIDOC ## to_where_part ### Description Builds the WHERE part of an SQL query. ### Method `to_where_part(criteria) ### Parameters - `criteria`: The conditions for the WHERE clause. ### Response Returns the SQL string for the WHERE clause. ``` ```APIDOC ## to_order_part ### Description Builds the ORDER BY part of an SQL query. ### Method `to_order_part(order_by) ### Parameters - `order_by`: The ordering criteria. ### Response Returns the SQL string for the ORDER BY clause. ``` ```APIDOC ## to_limit_part ### Description Builds the LIMIT part of an SQL query. ### Method `to_limit_part(limit) ### Parameters - `limit`: The limit value. ### Response Returns the SQL string for the LIMIT clause. ``` ```APIDOC ## to_find_sql ### Description Generates the SQL query string for finding records. ### Method `to_find_sql(model_type, criteria...; options...) ### Parameters - `model_type`: The type of model. - `criteria`: Conditions for finding records. - `options`: Additional query options. ### Response Returns the generated SQL query string. ``` -------------------------------- ### Convert Model to String Dictionary Source: https://context7.com/genieframework/searchlight.jl/llms.txt Converts a SearchLight model instance into a dictionary where values are represented as strings, including type information. Useful for specific serialization needs. ```julia SearchLight.to_string_dict(u) # => Dict("id::DbId" => "1", "username::String" => "temp", ...) ``` -------------------------------- ### new_table_migration Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/filetemplates.md Generates a new migration file for creating a database table. ```APIDOC ## new_table_migration ### Description Generates a new migration file for creating a database table. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### newtest Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/filetemplates.md Generates a new test file. ```APIDOC ## newtest ### Description Generates a new test file. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### Find or Create Model Instance Source: https://context7.com/genieframework/searchlight.jl/llms.txt Use `findone_or_create` to find an existing record or build a new unsaved instance with the given fields. The new instance is not saved automatically. ```julia # Returns existing record or a new unsaved instance with given fields set user = findone_or_create(User, username = "eve") ispersisted(user) || save!(user) ``` -------------------------------- ### MissingDatabaseConfigurationException Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/exceptions.md Exception raised when the database configuration is missing or incomplete. ```APIDOC ## MissingDatabaseConfigurationException ### Description This exception indicates that the necessary configuration for connecting to the database is not found or is incomplete. Ensure that your database connection settings are correctly defined in the application's configuration files. ### Type Exception ### Inheritance Inherits from `SearchLightException`. ``` -------------------------------- ### SQL String Interpolation Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/modeltypes.md Provides a macro for creating SQL strings with interpolation, allowing for safer and more convenient SQL query construction. ```APIDOC ## SQL String Interpolation ### Macro - **@sql_str**: A macro for creating SQL strings with interpolation. This macro helps in constructing SQL queries by allowing variables to be embedded directly into the SQL string, often with automatic type handling and escaping to prevent SQL injection vulnerabilities. ``` -------------------------------- ### Override Environment Configuration Source: https://context7.com/genieframework/searchlight.jl/llms.txt Programmatically overrides the application environment setting by modifying the ENV["SEARCHLIGHT_ENV"] variable. This takes precedence over settings in connection.yml. ```julia ENV["SEARCHLIGHT_ENV"] = "prod" ``` -------------------------------- ### create_relationship_migration Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/relationships.md Generates a migration file for creating or updating relationship tables. ```APIDOC ## create_relationship_migration ### Description Creates a new migration file to define or modify relationship tables in the database. ### Function Signature ```julia create_relationship_migration(migration_name::String, relationship_definitions::Dict{String, Any}) ``` ### Parameters #### Positional Arguments - **migration_name** (String) - The name of the migration file to be created. - **relationship_definitions** (Dict{String, Any}) - A dictionary containing the definitions of the relationships to be included in the migration. ### Usage Example ```julia create_relationship_migration("add_user_posts_relationship", Dict("User" => Dict("posts" => Dict("type" => "has_many", "target" => "Post")))) ``` ``` -------------------------------- ### resource_does_not_exist Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/generator.md Checks if a resource does not exist. ```APIDOC ## resource_does_not_exist ### Description Checks if a resource does not exist. ### Method ```julia resource_does_not_exist(name::String) ``` ``` -------------------------------- ### newmodel Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/generator.md Creates a new data model definition. ```APIDOC ## newmodel ### Description Creates a new data model definition. ### Method ```julia newmodel(name::String) ``` ``` -------------------------------- ### Retrieve All Records with `all` Source: https://context7.com/genieframework/searchlight.jl/llms.txt Fetches all rows for a given model, supporting optional ordering, limiting, and offsetting for pagination. Can also select specific columns. ```julia # All records all_users = all(User) # With pagination page_2 = all(User, limit = 20, offset = 20, order = SQLOrder(:username)) # Specific columns only cols = all(User, columns = [SQLColumn(:id), SQLColumn(:username)]) ``` -------------------------------- ### Migration Information and Status Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/migrations.md Functions to retrieve information about migrations, including hashes, file names, and status. ```APIDOC ## Migration Information and Status ### `migration_hash(migration::DatabaseMigration)` Returns the hash of a migration. ### `migration_file_name(migration::DatabaseMigration)` Returns the file name of a migration. ### `migration_module_name(migration::DatabaseMigration)` Returns the module name of a migration. ### `last_up()` Returns the last migration that was successfully applied (upwards). ### `lastup()` Alias for `last_up`. ### `last_down()` Returns the last migration that was reverted (downwards). ### `lastdown()` Alias for `last_down`. ### `all_migrations()` Returns a list of all available migrations. ### `all()` Alias for `all_migrations`. ### `last_migration()` Returns the most recent migration. ### `last()` Alias for `last_migration`. ### `upped_migrations()` Returns a list of migrations that have been applied upwards. ### `downed_migrations()` Returns a list of migrations that have been reverted downwards. ### `status()` Returns the status of all migrations. ### `all_with_status()` Returns all migrations along with their status. ``` -------------------------------- ### QueryBuilder DSL Source: https://context7.com/genieframework/searchlight.jl/llms.txt Provides a chainable API for composing SQL queries using the `+` operator. ```APIDOC ## QueryBuilder (Composable DSL) ### `from` / `select` / `where` / `order` / `limit` / `offset` / `group` / `having` / `prepare` The `QueryBuilder` module exposes a chainable query API using the `+` operator to compose `QueryPart` values. ### Usage ```julia using SearchLight.QueryBuilder # Compose query parts with + qp = from(User) + where("active = ?", true) + order(:username) + limit(10) + offset(0) users = find(User, qp) # Select specific columns qp2 = from(User) + select(:username, :email) + where("age >= ?", 18) + order(:age, :desc) users2 = find(User, qp2) # Reuse a base query and extend it base = where("active = ?", true) + order(:username) page1 = find(User, from(User) + base + limit(20) + offset(0)) page2 = find(User, from(User) + base + limit(20) + offset(20)) # Inspect SQL println(SearchLight.sql(User, from(User) + where("age > ?", 30))) ``` ``` -------------------------------- ### Persist Model with `save` Source: https://context7.com/genieframework/searchlight.jl/llms.txt Use `save` to persist a model to the database. It returns `true` on success and `false` on failure. Validation and callbacks can be skipped, and conflict strategies can be defined. ```julia user = User(username = "bob", email = "bob@example.com", age = 25) if save(user) println("Saved successfully") else println("Save failed — check logs") end ``` ```julia # Skip validation or callbacks selectively save(user, skip_validation = true) save(user, skip_callbacks = [:before_save, :after_save]) ``` ```julia # Conflict strategy: :error (default), :ignore, :replace save(user, conflict_strategy = :ignore) ``` -------------------------------- ### SQLJoin for Fetching Related Data Source: https://context7.com/genieframework/searchlight.jl/llms.txt Define SQL JOIN clauses to fetch related data from multiple tables. Specify join type, conditions, and desired columns. ```julia # Fetch Articles with their author User data joins = [ SQLJoin(User, SQLOn("articles.user_id", "users.id"), join_type = SQLJoinType("LEFT"), columns = [SQLColumn("users.username AS author_name")]) ] q = SQLQuery(where = [SQLWhereExpression("articles.active = ?", true)]) articles = find(Article, q, joins) ``` -------------------------------- ### Sequence and Constraint Management Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/migrations.md Functions for managing database sequences and constraints. ```APIDOC ## Sequence and Constraint Management ### `create_sequence(name::Symbol, options::Dict=Dict())` Creates a new database sequence. ### `constraint(name::Symbol, definition::String, options::Dict=Dict())` Defines a database constraint. ### `nextval(sequence_name::Symbol)` Retrieves the next value from a sequence. ### `column_id_sequence(name::Symbol=:id)` Returns the sequence associated with an auto-incrementing ID column. ### `remove_sequence(name::Symbol, options::Dict=Dict())` Removes a database sequence. ### `drop_sequence(name::Symbol, options::Dict=Dict())` Alias for `remove_sequence`. ``` -------------------------------- ### SQL Query Construction Types Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/modeltypes.md Provides types for building complex SQL queries, including operators, WHERE clauses, limits, ordering, joins, and raw SQL. ```APIDOC ## SQL Query Construction Types These types facilitate the programmatic construction of SQL queries. ### Types - **SQLLogicOperator**: Represents logical operators used in SQL (e.g., AND, OR). - **SQLWhere**: Represents a WHERE clause in a SQL query. - **SQLWhereExpression**: Represents an expression within a WHERE clause. - **SQLWhereEntity**: Represents an entity within a WHERE clause condition. - **SQLLimit**: Represents the LIMIT clause in a SQL query. - **SQLOrder**: Represents the ORDER BY clause in a SQL query. - **SQLQuery**: Represents a complete SQL query. - **SQLRaw**: Represents raw SQL fragments. - **SQLJoin**: Represents a JOIN clause. - **SQLOn**: Represents the ON condition for a JOIN. - **SQLJoinType**: Represents the type of JOIN (e.g., INNER, LEFT). - **SQLHaving**: Represents the HAVING clause in a SQL query. ``` -------------------------------- ### Define ORM Models Source: https://context7.com/genieframework/searchlight.jl/llms.txt Defines database models by creating mutable structs that subtype `AbstractModel` and include an `id::DbId` primary key. The `@kwdef` macro provides keyword constructors. ```julia import SearchLight: AbstractModel, DbId import Base: @kwdef @kwdef mutable struct User <: AbstractModel id::DbId = DbId() username::String = "" email::String = "" age::Int = 0 active::Bool = true end @kwdef mutable struct Article <: AbstractModel id::DbId = DbId() title::String = "" body::String = "" user_id::Int = 0 end # DbId wraps an Int, String, or nothing (for unsaved records) u = User(username = "alice", email = "alice@example.com", age = 30) u.id # => NULL (not yet saved) u.id.value # => nothing ``` -------------------------------- ### new_relationship_table_migration Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/filetemplates.md Generates a new migration file for creating a relationship table between two other tables. ```APIDOC ## new_relationship_table_migration ### Description Generates a new migration file for creating a relationship table between two other tables. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### Generate New Migration Source: https://context7.com/genieframework/searchlight.jl/llms.txt Generates a new migration file with a timestamp. Use this to create database schema changes. ```julia Generator.newmigration("add_index_to_articles_title") ``` -------------------------------- ### Database Transactions in SearchLight.jl Source: https://context7.com/genieframework/searchlight.jl/llms.txt Wrap database operations within a transaction to ensure atomicity; operations are rolled back automatically if any exception occurs. ```julia using SearchLight.Transactions # transaction and with_transaction are aliases transaction() do u = save!(User(username = "henry", email = "henry@example.com", age = 29)) a = save!(Article(title = "My First Post", body = "Hello!", user_id = u.id.value)) # If any save! throws, the whole block is rolled back end # Example with deliberate error handling try with_transaction() do user = save!(User(username = "ivan", email = "ivan@example.com", age = 33)) # This would throw and trigger rollback: save!(Article(title = "", body = "No title!")) end catch ex println("Transaction rolled back: $ex") end ``` -------------------------------- ### on_find Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/callbacks.md Callback function executed after a find operation completes. ```APIDOC ## on_find ### Description Callback function executed after a find operation completes. ### Method Not applicable (function signature) ### Signature on_find(model, results) ### Parameters - **model**: The model instance used for the find operation. - **results**: The results returned by the find operation. ``` -------------------------------- ### QueryBuilder Types and Functions Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/querybuilder.md Overview of the core types and functions used in QueryBuilder. ```APIDOC ## Types ### `MissingModel` Represents a missing model in a query. ### `QueryPart` Abstract type for parts of a query. ## Functions ### `from` Specifies the table to query from. ### `select` Specifies the columns to select. ### `where` Adds a WHERE clause to the query. ### `limit` Limits the number of results. ### `offset` Specifies the offset for results. ### `order` Specifies the order of results. ### `group` Groups results by specified columns. ### `having` Adds a HAVING clause to the query. ### `prepare` Prepares the query for execution. ### `+` (Operator) Used for combining query parts. ### `DataFrames.DataFrame` Represents data in a tabular format, often used as a return type. ### `SearchLight.find` Executes a query and returns multiple results. ### `SearchLight.first` Executes a query and returns the first result. ### `SearchLight.last` Executes a query and returns the last result. ### `SearchLight.count` Executes a query and returns the count of results. ### `SearchLight.sql` Returns the raw SQL string for the built query. ``` -------------------------------- ### Introspection Helpers Source: https://context7.com/genieframework/searchlight.jl/llms.txt Utility functions for inspecting database tables, primary keys, persistence status, and generating SQL. ```APIDOC ## Utility Functions ### `table` / `pk` / `ispersisted` / `sql` — Introspection helpers These functions help in introspecting database models and queries. ```julia using SearchLight # Get the DB table name for a model SearchLight.table(User) # => "users" SearchLight.table(Article) # => "articles" # Get the primary key field name SearchLight.pk(User) # => "id" # Check if a model instance is saved in the DB u = User(username = "temp") SearchLight.ispersisted(u) # => false u = save!(u) SearchLight.ispersisted(u) # => true # Generate the SQL string for a query without executing it q = SQLQuery(where = [SQLWhereExpression("age > ?", 30)], limit = 5) println(SearchLight.sql(User, q)) # => SELECT "users"."id" AS "users_id", ... FROM "users" WHERE age > 30 LIMIT 5 # Convert a model to a Dict SearchLight.to_dict(u) # => Dict("id" => DbId(1), "username" => "temp", ...) SearchLight.to_string_dict(u) # => Dict("id::DbId" => "1", "username::String" => "temp", ...) ``` ``` -------------------------------- ### write_resource_file Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/generator.md Writes a resource file. ```APIDOC ## write_resource_file ### Description Writes a resource file. ### Method ```julia write_resource_file(resource::String, path::String) ``` ``` -------------------------------- ### Query Multiple Records with `find` Source: https://context7.com/genieframework/searchlight.jl/llms.txt Retrieves multiple model instances matching specified conditions. Supports keyword filters, SQLWhereExpressions, and explicit SQLQuery objects for complex queries. ```julia using SearchLight, Dates # All users users = find(User) # => Vector{User}[...] # Keyword filter (simple equality) active_users = find(User, active = true) # SQLWhereExpression with ? placeholders adults = find(User, SQLWhereExpression("age >= ?", 18)) # Multiple conditions with AND results = find(User, SQLWhereExpression("age >= ? AND active = ?", 18, true)) # Date range query with ordering start_date = Date("2024-01-01") end_date = Date("2024-12-31") articles = find(Article, SQLWhereExpression("created_at >= ? AND created_at <= ?", start_date, end_date), order = ["articles.created_at"]) # With explicit SQLQuery for full control q = SQLQuery( where = [SQLWhereExpression("age BETWEEN ? AND ?", [20, 40])], order = [SQLOrder(:username, :asc)], limit = SQLLimit(10), offset = 20 ) users = find(User, q) ``` -------------------------------- ### Convert Model to Dictionary Source: https://context7.com/genieframework/searchlight.jl/llms.txt Converts a SearchLight model instance into a dictionary representation. This is useful for serialization or data manipulation. ```julia SearchLight.to_dict(u) # => Dict("id" => DbId(1), "username" => "temp", ...) ``` -------------------------------- ### Database Connection Management Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/searchlight.md Functions for managing database connections, including establishing and closing connections. ```APIDOC ## connect ### Description Establishes a connection to the database. ### Method `connect()` ### Parameters None explicitly documented. ### Response Returns a database connection object. ## disconnect ### Description Closes the active database connection. ### Method `disconnect()` ### Parameters None explicitly documented. ### Response None explicitly documented. ## connection ### Description Retrieves the current active database connection. ### Method `connection()` ### Parameters None explicitly documented. ### Response Returns the active database connection object. ``` -------------------------------- ### Generator Functions Source: https://context7.com/genieframework/searchlight.jl/llms.txt Functions to generate new migrations and configuration files. ```APIDOC ## Generator Functions ### `Generator.newmigration` Creates a blank migration file. ```julia Generator.newmigration("add_index_to_articles_title") # Creates: db/migrations/_add_index_to_articles_title.jl ``` ### `Generator.newconfig` Generates a default `connection.yml` configuration file. ```julia Generator.newconfig() # Creates: db/connection.yml ``` ``` -------------------------------- ### Code Generation Source: https://context7.com/genieframework/searchlight.jl/llms.txt The `Generator` module provides utilities to scaffold new application components, including models, migrations, validators, and tests, helping to streamline the development process. ```APIDOC ## Code Generation ### `Generator.newresource` / `newmodel` / `newmigration` — Scaffold files ```julia using SearchLight.Generator # Generate a model + migration + validator + test files Generator.newresource("Article") # Creates: # app/resources/articles/Articles.jl # app/resources/articles/ArticlesValidator.jl # test/articles_test.jl # db/migrations/_create_table_articles.jl # Generate model file only Generator.newmodel("Comment") ``` ``` -------------------------------- ### SQL Utility Functions Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/searchlight.md Helper functions for SQL string manipulation and escaping. ```APIDOC ## escape_column_name ### Description Escapes a column name for safe use in SQL queries. ### Method `escape_column_name(name) ### Parameters - `name`: The column name to escape. ### Response Returns the escaped column name. ``` ```APIDOC ## escape_value ### Description Escapes a value for safe use in SQL queries. ### Method `escape_value(value) ### Parameters - `value`: The value to escape. ### Response Returns the escaped value. ``` ```APIDOC ## add_quotes ### Description Adds quotes around a string, typically for SQL identifiers. ### Method `add_quotes(str) ### Parameters - `str`: The string to quote. ### Response Returns the quoted string. ``` -------------------------------- ### new_table_migration Source: https://github.com/genieframework/searchlight.jl/blob/master/docs/src/API/generator.md Creates a new migration for a table. ```APIDOC ## new_table_migration ### Description Creates a new migration for a table. ### Method ```julia new_table_migration(name::String) ``` ``` -------------------------------- ### Upsert Records with `update_or_create` / `updateby_or_create` Source: https://context7.com/genieframework/searchlight.jl/llms.txt Use `update_or_create` to update an existing record or create a new one based on the model's primary key. Use `updateby_or_create` to look up by filters and update or create. Updates can be skipped. ```julia # update_or_create uses the model's pk to decide insert vs update user = User(username = "frank", email = "frank@example.com", age = 35) user = update_or_create(user) ``` ```julia # updateby_or_create looks up by given filters and updates or creates user = User(username = "grace", email = "grace@example.com", age = 27) user = updateby_or_create(user, username = "grace") ``` ```julia # Skip updating existing records — only create if not found user = updateby_or_create(user, skip_update = true, username = "grace") ```