### Install pg-generator-example generator Source: https://pg-generator.com/nav.01.guide/01.getting-started Step 4: Install a generator that contains templates. If pg-generator was installed globally, install the generator globally too. pg-generator-example provides example generators. ```bash $ npm install -g pg-generator-example ``` -------------------------------- ### Install pg-generator CLI Source: https://pg-generator.com/ Installs the pg-generator CLI globally along with the example generator package. Requires Node.js and npm. ```bash $ npm install -g pg-generator@5.0.0-alpha.8 pg-generator-example ``` -------------------------------- ### Install pg-generator and nunjucks Source: https://pg-generator.com/nav.03.creating-generators/01.getting-started.html Installs the latest version of pg-generator and the nunjucks templating engine used in the examples. Any template engine can be used instead. ```bash $ npm install pg-generator nunjucks ``` -------------------------------- ### Include schemas with pattern: pgen example -i: "public_%" Source: https://pg-generator.com/nav.01.guide/02.advanced.html Includes all schemas starting with 'public_' using the includeSchemas option with a pattern. ```bash $ pgen example -i: "public_%" ``` -------------------------------- ### wordWrap examples Source: https://pg-generator.com/api-site/modules/filterfunctions Word wraps the given text. The first example wraps at a specified width, and the second example uses a start position for indentation. ```typescript wordWrap("The quick fox", 10); // "The quick\nfox" wordWrap("The quick fox", 2, 10); // " The quick\n fox" ``` -------------------------------- ### linePrefix example Source: https://pg-generator.com/nav.02.api/modules/filterfunctions Adds a prefix to each line of a multi-line string. The example shows adding '// ' to two lines, resulting in commented lines. ```javascript linePrefix(` Text line 1 Text line 2 `, "// "); // Text line 1 // Text line 2 ``` -------------------------------- ### CLI command: pgen example --outDir models Source: https://pg-generator.com/nav.01.guide/02.advanced.html Runs pg-generator as a CLI tool with the example generator, outputting to the models directory. ```bash $ pgen example --outDir models ``` -------------------------------- ### init() Source: https://pg-generator.com/nav.03.creating-generators/03.generators.html Called after clear and before any other operation. Override to perform setup tasks such as making backups. ```APIDOC ## init() ### Description Called after `clear` and before any other operation. Override to perform setup tasks such as making backups. ### Method init() ### Parameters None ### Example ```typescript import { join } from "path"; import { copy } from "fs-extra"; export default class App extends PgGenerator { protected async init(): Promise { await copy(this.destinationPath(), join(this.destinationPath(), "-backup")); } } ``` ``` -------------------------------- ### linePrefix example Source: https://pg-generator.com/api-site/modules/filterfunctions Adds a prefix to each line of text. Example: linePrefix with prefix "// " adds it to each line. ```typescript linePrefix(` Text line 1 Text line 2 `, "// "); // Text line 1 // Text line 2 ``` -------------------------------- ### Template file tree example Source: https://pg-generator.com/nav.01.guide Shows the structure of template files for a generator. Brackets [] define the database object, braces {} define the output file name, and # is used for filtering/converting the file name. The example includes a template for the database, tables, and views. ```text └─ [db] index.js.njk └─ models/ └─ [table] {schema.name # dash-case}{name # dash-case}.js.njk └─ [view] {name # dash-case}.js.njk ``` -------------------------------- ### quote example Source: https://pg-generator.com/api-site/modules/filterfunctions Wraps the given string with double quotes. The example shows the output for the input 'user_name'. ```javascript plural("user_name"); // "user_name" ``` -------------------------------- ### pascalCase example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts the input string to Pascal case. For example, 'user-name' becomes 'UserName'. ```javascript pascalCase("user-name"); // UserName ``` -------------------------------- ### wrap example Source: https://pg-generator.com/nav.02.api/modules/filterfunctions Wraps given text with start and end characters. By default it uses curly braces. The second call uses '~' as wrapper, and the third uses '[]'. ```javascript wrap("hello"); // "{hello}" wrap("hello", "~"); // "~hello~" wrap("hello", "[]"); // "[hello]" ``` -------------------------------- ### Install pg-generator globally Source: https://pg-generator.com/nav.01.guide/01.getting-started Step 3: Install pg-generator globally with npm. If installed globally, the pgen command is available anywhere. ```bash $ npm install -g pg-generator` ``` -------------------------------- ### Add database credentials to .env Source: https://pg-generator.com/nav.01.guide/01.getting-started Step 2 (continued): Add database credentials to the .env file. Replace the example values with your own. ```env DB_DATABASE=example DB_HOST=localhost DB_USER=user DB_PASSWORD=password ``` -------------------------------- ### Install pg-generator with npm Source: https://pg-generator.com/api-site Installs pg-generator version 5.0.0-alpha.9 globally along with the pg-generator-example package. Use this to set up the tool for command-line use. ```bash $ npm install -g pg-generator@5.0.0-alpha.9 pg-generator-example ``` -------------------------------- ### fill example Source: https://pg-generator.com/api-site/modules/filterfunctions Completes input length with a character (default space). Example: completeWithChar("member", "10") returns "member " and completeWithChar("member", "10", "-") returns "member----". ```typescript completeWithChar("member", "10"); // "member " completeWithChar("member", "10", "-"); // "member----" ``` -------------------------------- ### singular example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts the input string to its singular form. For example, 'user_names' becomes 'user_name'. ```javascript singular("user_names"); // user_name ``` -------------------------------- ### Complete generator structure example Source: https://pg-generator.com/nav.03.creating-generators Shows the full directory structure of a generator with partials, utils, app and report sub-generators. This structure enables 'pgen name' and 'pgen name:report' commands. ```text ├─ package.json └─ dist/ ├─ partials/ ├─ utils/ ├─ app/ │ ├─ index.js │ └─ templates/ │ ├─ partials/ │ ├─ README.md │ ├─ [db] index.js.njk │ └─ models/ │ ├─ [table] {schema.name # dash-case}{name # dash-case}.js.njk │ └─ [view] {name # dash-case}.js.njk └─ report/ ├─ index.js └─ templates/ └─ [db] report.md.njk ``` -------------------------------- ### lcFirst example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts the first letter to lower case. Example: plural("User_name") returns "User_name". ```typescript plural("User_name"); // User_name ``` -------------------------------- ### singleQuote example Source: https://pg-generator.com/api-site/modules/filterfunctions Wraps the given string with single quotes, escaping any single quotes inside. The example shows the output for the input "Some 'example' text". ```javascript plural("Some 'example' text"); // 'some \'example\' text' ``` -------------------------------- ### Override init() to make a backup before writing Source: https://pg-generator.com/nav.03.creating-generators/03.generators.html Called after clear and before any other operation. This example copies the destination directory to a '-backup' folder. ```typescript import { join } from "path"; import { copy } from "fs-extra"; export default class App extends PgGenerator { protected async init(): Promise { await copy(this.destinationPath(), join(this.destinationPath(), "-backup")); } } ``` -------------------------------- ### wordWrap example Source: https://pg-generator.com/nav.02.api/modules/filterfunctions Word wraps given text. The first call wraps at position 10, producing a newline. The second call uses start position 2 and stop position 10, indenting each line with two spaces. ```javascript wordWrap("The quick fox", 10); // "The quick\nfox" wordWrap("The quick fox", 2, 10); // " The quick\n fox" ``` -------------------------------- ### snakeCase example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts the input string to snake case. For example, 'userName' becomes 'user_name'. ```javascript snakeCase("userName"); // user_name ``` -------------------------------- ### plural example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts the input string to its plural form. For example, 'user_name' becomes 'user_names'. ```javascript plural("user_name"); // user_names ``` -------------------------------- ### quote example Source: https://pg-generator.com/nav.02.api/modules/filterfunctions Wraps a string with double quotes. The example shows using plural() but the function is quote(). ```javascript plural("user_name"); // "user_name" ``` -------------------------------- ### Generated file tree example Source: https://pg-generator.com/nav.01.guide Shows the resulting file tree after running pg-generator with the template files. The output includes index.js and model files for each table and view, with names converted to dash-case. ```text └─ index.js └─ models/ ├─ public.customer.js ├─ public.delivery-address.js ├─ public.line-item.js └─ view-vip-customer.js ``` -------------------------------- ### wrapIf example Source: https://pg-generator.com/nav.02.api/modules/filterfunctions Wraps given text with start and end characters if the condition is truthy. By default it uses curly braces. The examples show wrapping when condition is truthy, not wrapping when falsy, and custom wrappers. ```javascript wrapIf("hello", "x"); // "{hello}" wrapIf("hello", true); // "{hello}" wrapIf("hello", false); // "hello" wrapIf("hello", true, "~"); // "~hello~" wrapIf("hello", true, "[]"); // "[hello]" ``` -------------------------------- ### CLI command with contextFile: pgen example:sequelize6 --contextFile Source: https://pg-generator.com/nav.01.guide/02.advanced.html Runs the sequelize6 sub-generator with a context file to override template configuration, such as global.addSchemaName. ```bash $ pgen example:sequelize6 --outDir models --contextFile path/to/my-context.js ``` -------------------------------- ### wrap examples Source: https://pg-generator.com/api-site/modules/filterfunctions Wraps the input with a wrapper string. Default wrapper is curly braces, but custom wrappers can be specified. ```typescript wrap("hello"); // "{hello}" wrap("hello", "~"); // "~hello~" wrap("hello", "[]"); // "[hello]" ``` -------------------------------- ### classCase example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts a string to class case. Example: classCase("user-name") returns "UserName". ```typescript classCase("user-name"); // UserName ``` -------------------------------- ### Create generator directory and change into it Source: https://pg-generator.com/nav.03.creating-generators/01.getting-started.html Creates a new directory starting with 'pg-generator' and changes into it. This is the first step of the manual creation method. ```bash $ mkdir pg-generator-awesome && cd pg-generator-awesome ``` -------------------------------- ### titleCase example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts a string to title case. The example shows that underscores are replaced with spaces and each word is capitalized. ```typescript titleCase("user_name"); // User Name ``` -------------------------------- ### doubleQuote example Source: https://pg-generator.com/api-site/modules/filterfunctions Wraps a string with double quotes. Example: plural("Some \"example\" text") returns "some \"example\" text". ```typescript plural("Some "example" text"); // "some \"example\" text" ``` -------------------------------- ### dashCase example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts a string to dash case. Example: dashCase("User Name") returns "user-name". ```typescript dashCase("User Name"); // user-name ``` -------------------------------- ### camelCase example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts a string to camel case. Example: camelCase("user-name") returns "userName". ```typescript camelCase("user-name"); // userName ``` -------------------------------- ### API call: await generate("example", { outDir: "models" }) Source: https://pg-generator.com/nav.01.guide/02.advanced.html Equivalent to the CLI command, using the pg-generator API within Node.js. The generate function is async and takes the same options. ```javascript await generate("example" { outDir: "models" }); ``` -------------------------------- ### ucFirst example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts the first letter of the input to uppercase. The example uses 'plural' instead of 'ucFirst', which appears to be a typo in the source. ```typescript plural("user_name"); // User_name ``` -------------------------------- ### Include multiple schemas: pgen example -i public -i extra Source: https://pg-generator.com/nav.01.guide/02.advanced.html Includes only the 'public' and 'extra' schemas by using the -i alias multiple times. ```bash $ pgen example -i public -i extra ``` -------------------------------- ### human example Source: https://pg-generator.com/api-site/modules/filterfunctions Converts text to natural language. Example: human("message_properties") returns "Message properties" and human("message_properties", true) returns "message properties". ```typescript human("message_properties"); // "Message properties" human("message_properties", true); // "message properties" ``` -------------------------------- ### Run sub-generator via CLI Source: https://pg-generator.com/nav.01.guide/01.getting-started Step 5 (CLI): Run a sub-generator by adding its name after a colon. This example runs the 'report' sub-generator. ```bash $ pgen example:report --out-dir reports --clear ``` -------------------------------- ### generate function example Source: https://pg-generator.com/api-site/modules Executes the default sub-generator `app` from a generator. The generator parameter can be a name or a path; for local paths, use `require.resolve` or provide an absolute path. ```javascript generate("generator-from-npm", options); generate(require.resolve("./local-generator"), options); ``` -------------------------------- ### Special context keys for targeting specific database objects Source: https://pg-generator.com/nav.03.creating-generators/02.templates Example context object showing how to send data to specific templates using database object names in plural. Here, `skip: true` is sent only to table templates for `public.product`, and `message: "Hello!"` to schema templates for `public`. ```json { "tables": { "public.product": { "skip": true } }, "schemas": { "public": { "message": "Hello!" } } } ``` -------------------------------- ### Override process() to post content to a server Source: https://pg-generator.com/nav.03.creating-generators/03.generators.html Writes content to the destination file by default. This rough example posts the content to a server instead of writing to disk. ```typescript import { post } from "axios"; import { basename } from "path"; export default class Md extends PgGenerator { protected process(destination: string, content: string): Promise | any { await post(`http://myserver.com/model/${basename(destination)}`, content); } } ``` -------------------------------- ### composeWith - named sub-generator example Source: https://pg-generator.com/api-site/classes/pggenerator Composes a named sub-generator with merged options)Skip from the previous example, this overload sets default values for some options (e.g., clear set to false). Throws an error if the generator or sub-generator is not found. ```typescript this.composeWith("generator-from-npm", "sub-generator"); this.composeWith(require.resolve("./local-generator"), "sub-generator", options); ``` -------------------------------- ### wrapIf examples Source: https://pg-generator.com/api-site/modules/filterfunctions Wraps the input with a wrapper only if the condition is truthy. Default wrapper is curly braces. ```typescript wrapIf("hello", "x"); // "{hello}" wrapIf("hello", true); // "{hello}" wrapIf("hello", false); // "hello" wrapIf("hello", true, "~"); // "~hello~" wrapIf("hello", true, "[]"); // "[hello]" ``` -------------------------------- ### clearDefault example Source: https://pg-generator.com/api-site/modules/filterfunctions Clears the default value of a database object. Example: clearDefaultValue("'No ''value'' given'") returns "No value 'given'". ```typescript clearDefaultValue("'No ''value'' given'"); // "No value 'given'" ``` -------------------------------- ### Run sub-generator via API Source: https://pg-generator.com/nav.01.guide/01.getting-started Step 5 (API): Use the generate function with a sub-generator name as the second parameter. This example runs the 'report' sub-generator. ```javascript import { generate } from "pg-generator"; await generate("example", "report", { outDir: "reports", clear: true }); ``` -------------------------------- ### dboColumnTypeModifier example Source: https://pg-generator.com/api-site/modules/filterfunctions Returns column length, precision and scale ready for templates. Example: columnTypeModifier(price) returns "(10,4)" and columnTypeModifier(name) returns "(20)". ```typescript columnTypeModifier(price); // (10,4) columnTypeModifier(name); // (20) ``` -------------------------------- ### Link the generator module globally with npm link Source: https://pg-generator.com/nav.03.creating-generators/01.getting-started.html Symlinks the generator as if installed globally. Run from the root of the module where package.json is located. ```bash $ npm link ``` -------------------------------- ### composeWith - default sub-generator example Source: https://pg-generator.com/api-site/classes/pggenerator Composes the default 'app' sub-generator from a generator, with optional merged options. Use for running a sub-generator from an npm package or a local path resolved with require.resolve. Throws an error if the generator cannot be found. ```typescript this.composeWith("generator-from-npm"); this.composeWith("generator-from-npm", options); this.composeWith(require.resolve("./local-generator"), options); ``` -------------------------------- ### stripPrefix Source: https://pg-generator.com/api-site/modules/filterfunctions Strips all of the given strings or database object's names from the start of the source string. ```APIDOC ## stripPrefix ### Description Variadic function which strips all of the given strings or database object's names from the start of the source string. ### Function Signature `stripPrefix(input: string | undefined, ...removeList: (string | { name: string })[]): string` ### Parameters - `input` (string | undefined) - Required - The input string to convert. - `...removeList` ((string | { name: string })[]) - Required - The list of strings or objects to remove from input. ### Returns - (string) - Converted string. ``` -------------------------------- ### wrap Source: https://pg-generator.com/api-site/modules/filterfunctions Wraps given text with start and end characters. By default it wraps with curly braces. ```APIDOC ## wrap ### Description Wraps given text with start and end characters. By default it wraps with curly braces. ### Function Signature `wrap(input?: string, wrapper?: string): string` ### Parameters - `input` (string) - Optional - The text to warp. - `wrapper` (string) - Optional - Default: "{}" ### Returns - (string) - Wrapped text. ### Example ```js wrap("hello"); // "{hello}" wrap("hello", "~"); // "~hello~" wrap("hello", "[]"); // "[hello]" ``` ``` -------------------------------- ### maxLength example Source: https://pg-generator.com/api-site/modules/filterfunctions Cuts the input string after the given number of characters and appends an ellipsis. The default length is 50. ```javascript maxLength("some example text", 7); // "some ex..."; ``` -------------------------------- ### listAttribute example Source: https://pg-generator.com/api-site/modules/filterfunctions Shows how to extract an attribute from an array of objects and join them into a CSV string. Options allow quoting (single, double, or JSON) and wrapping the list when length is greater than 1. ```javascript const objects = [{ name: "a" }, { name: "b" }, { name: "c" }] listAttribute(objects, "name"); // a, b, c listAttribute(objects, "name", { quote: "json" }); // "a", "b", "c" listAttribute(objects, "name", { quote: "single" }); // 'a', 'b', 'c' listAttribute(objects, "name", { quote: "json", wrap: "[]" }); // ["a", "b", "c"] listAttribute(objects, "name", { quote: "json", wrap: "[]" }); // "a" ``` -------------------------------- ### Create project directory and navigate into it Source: https://pg-generator.com/nav.01.guide/01.getting-started Step 1: Create a new directory and change into it. ```bash $ mkdir my-project && cd my-project ``` -------------------------------- ### Scaffold a custom generator with pgen-scaffold Source: https://pg-generator.com/api-site Creates a new generator project using the nunjucks template engine, outputting to the specified directory. Use this to start building your own tailored generators. ```bash $ pgen-scaffold nunjucks --outDir my-project ``` -------------------------------- ### wrapIf Source: https://pg-generator.com/api-site/modules/filterfunctions Wraps given text with start and end characters if given condition is truthy. By default it wraps with curly braces. ```APIDOC ## wrapIf ### Description Wraps given text with start and end characters if given condition is truthy. By default it wraps with curly braces. ### Function Signature `wrapIf(input: string | undefined, condition: any, wrapper?: string): string` ### Parameters - `input` (string | undefined) - Required - The text to warp. - `condition` (any) - Required - The condition or value to test. - `wrapper` (string) - Optional - Default: "{}" ### Returns - (string) - Wrapped text. ### Example ```js wrapIf("hello", "x"); // "{hello}" wrapIf("hello", true); // "{hello}" wrapIf("hello", false); // "hello" wrapIf("hello", true, "~"); // "~hello~" wrapIf("hello", true, "[]"); // "[hello]" ``` ``` -------------------------------- ### Using converters.mermaidToSVG in a custom render method Source: https://pg-generator.com/nav.03.creating-generators/06.converters.html This example shows how to use the mermaidToSVG converter to convert Mermaid diagrams in the rendered content. It is used when filter functions are not sufficient for operating on individual strings. ```typescript import { PgGenerator, Context, converters } from "pg-generator"; export default class App extends PgGenerator { protected async render(templatePath: string, context: Context): Promise { const content = nunjucks.render(templatePath, context); return converters.mermaidToSVG(content); } } ``` -------------------------------- ### Create .env file Source: https://pg-generator.com/nav.01.guide/01.getting-started Step 2: Create a .env file to store database credentials. ```bash $ touch .env ``` -------------------------------- ### generate function with sub-generator example Source: https://pg-generator.com/api-site/modules Executes a specific sub-generator from a generator. The generator parameter can be a name or a path; for local paths, use `require.resolve` or provide an absolute path. The subGenerator parameter specifies the sub-generator name, and options are added on top of current options. ```javascript generate("generator-from-npm", "sub-generator"); generate(require.resolve("./local-generator"), "sub-generator", options); ``` -------------------------------- ### Include schemas matching a pattern Source: https://pg-generator.com/api-site/interfaces/clientoptions Configures includeSchemas to include all schemas starting with 'public_' using a LIKE pattern. ```javascript const config = { includeSchemas: "public_%" }; // include all schemas starting with "public_" ``` -------------------------------- ### wordWrap(input?, startOrStop?, stop?) Source: https://pg-generator.com/nav.02.api/modules/filterfunctions Word wraps given text. The function inserts line breaks at specified positions, optionally with an indentation start position. ```APIDOC ## wordWrap(input?, startOrStop?, stop?) ### Description Word wraps given text. The function inserts line breaks at specified positions, optionally with an indentation start position. ### Method Function ### Signature `wordWrap(input?: string, startOrStop?: number, stop?: number): string` ### Parameters - **input?** (string) - Optional - The text to word wrap. - **startOrStop** (number) - Optional, default 80 - The start or stop position of each line. (The stop position if this is single option.) - **stop?** (number) - Optional - The stop position of each line. ### Returns - **string** - Word wrapped text. ### Example ``` wordWrap("The quick fox", 10); // "The quick\nfox" wordWrap("The quick fox", 2, 10); // " The quick\n fox" ``` ``` -------------------------------- ### Override render method with custom template engine Source: https://pg-generator.com/api-site/classes/pggenerator This example overrides the protected render method to use a custom template engine. It is defined in the context of the PgGenerator class. The method receives the templatePath and context, and should return the generated content as a string or undefined. ```typescript import engine from "my-favorite-template-engine"; export default class Md extends PgGenerator { protected async render(templatePath: string, context: Context): Promise { return engine.render(templatePath, context); } } ``` -------------------------------- ### context() method override example Source: https://pg-generator.com/api-site/classes/pggenerator Overrides the context method to provide generator-specific extra context for templates. The returned object is deeply merged with user-provided context. ```typescript export default class App extends PgGenerator { protected context(): Record { return { global: { addSchemaName: true } }; } } ``` -------------------------------- ### Using this.composeWith() to execute other generators Source: https://pg-generator.com/nav.03.creating-generators/04.composability.html The composeWith() method allows a generator to execute another generator. In this example, the App class composes two sub-generators (orm and report) by resolving their paths. The init() method returns a Promise.all() to execute both compositions concurrently. ```typescript export default class App extends PgGenerator { protected async init(): Promise { return Promise.all([this.composeWith(require.resolve("../orm")), this.composeWith(require.resolve("../report"))]); } } ``` -------------------------------- ### init() Source: https://pg-generator.com/nav.02.api/classes/pggenerator Protected method executed after clear operation. ```APIDOC ## init() ### Description Executed after clear operation. ### Method `Protected` `init` ### Returns _any_ ### Defined in pg-generator.ts:92 ``` -------------------------------- ### Set commentDataToken to extract JSON from comments Source: https://pg-generator.com/api-site/interfaces/clientoptions Configures the commentDataToken to extract JSON data from database object comments. The example assumes a comment like `[pg-structure]{ level: 3 }[/pg-structure]` and retrieves the data via `db.get("public.account").commentData`. ```javascript const config = { commentDataToken: "pg-structure" } // Assuming `[pg-structure]{ level: 3 }[/pg-structure]` is written in database table comment/description. const someData = db.get("public.account").commentData; // { level: 3 } ``` -------------------------------- ### constructor Source: https://pg-generator.com/api-site/classes/pggenerator Creates an instance of PgGenerator with user options and internal options. ```APIDOC ## constructor ### Description Creates an instance of PgGenerator. ### Method constructor ### Signature `new PgGenerator(options: O, internalOptions: InternalOptions): PgGenerator` ### Parameters - **options** (O) - Required - are parameters for several options. - **internalOptions** (InternalOptions) - Required - are added by `pg-generator` functions and not for user. ### Returns PgGenerator ``` -------------------------------- ### Create the default sub-generator app directory Source: https://pg-generator.com/nav.03.creating-generators/01.getting-started.html Creates the directory structure for the default sub-generator 'app' with a templates subdirectory. ```bash $ mkdir -p src/app/templates ``` -------------------------------- ### Create package.json for the generator module Source: https://pg-generator.com/nav.03.creating-generators/01.getting-started.html Defines the module's package.json with name, version, description, files, and keywords. The files array includes 'dist' and 'lib'. ```json { "name": "pg-generator-awesome", "version": "1.0.0", "description": "pg-generator for my favorite ORM models.", "files": ["dist", "lib"], "keywords": ["pg-generator"] } ``` -------------------------------- ### render(templatePath, context) Source: https://pg-generator.com/nav.03.creating-generators/03.generators.html The most important method. The template file's path and the context data are passed as parameters. Return rendered content using the template and the context. ```APIDOC ## render(templatePath, context) ### Description The most important method. The template file's path and the context data are passed as parameters. Return rendered content using the template and the context. ### Method render(templatePath, context) ### Parameters - **templatePath** (string) - Required - The path to the template file. - **context** (Context) - Required - The context data passed to the template. ### Returns - **Promise** - The rendered content. ### Example ```typescript import engine from "my-favorite-template-engine"; export default class Md extends PgGenerator { protected async render(templatePath: string, context: Context): Promise { return engine.render(templatePath, context); } } ``` ``` -------------------------------- ### process(destination, content) Source: https://pg-generator.com/nav.03.creating-generators/03.generators.html Writes given content to the given destination file. Override to change the default behavior, such as posting content to a server instead of writing to disk. ```APIDOC ## process(destination, content) ### Description Writes given content to the given destination file. Override to change the default behavior, such as posting content to a server instead of writing to disk. ### Method process(destination, content) ### Parameters - **destination** (string) - Required - The destination file path. - **content** (string) - Required - The content to write. ### Returns - **Promise | any** - The result of the write operation. ### Example ```typescript import { post } from "axios"; import { basename } from "path"; export default class Md extends PgGenerator { protected process(destination: string, content: string): Promise | any { await post(`http://myserver.com/model/${basename(destination)}`, content); } } ``` ``` -------------------------------- ### linePrefix(input?, prefix) Source: https://pg-generator.com/nav.02.api/modules/filterfunctions Adds a given prefix to each line of the input string. Returns the modified string. ```APIDOC ## linePrefix(input?, prefix) ### Description Adds the given prefix to each line of the input string. ### Method linePrefix ### Signature `linePrefix(input?: string, prefix: string): string` ### Parameters - **input** (string) - Optional, default "" - The input string. - **prefix** (string) - Required - The prefix to add to each line. ### Returns - **string** - The result string with prefix added to each line. ### Example ``` linePrefix(` Text line 1 Text line 2 `, "// "); // Text line 1 // Text line 2 ``` ``` -------------------------------- ### Run the generator with pgen command Source: https://pg-generator.com/nav.03.creating-generators/01.getting-started.html Executes the generator with the specified output directory, clear option, and database connection credentials. If collision errors occur, try --relationNameFunctions optimal or --relationNameFunctions optimal options. Prefer using a .env file instead of passing credentials via CLI options. ```bash $ pgen awesome --outDir db-docs --clear --host localhost --database db --user user --password password ``` -------------------------------- ### Run generator via CLI Source: https://pg-generator.com/nav.01.guide/01.getting-started Step 5 (CLI): Run the generator for your database. The --out-dir option specifies the output directory and --clear clears the output directory before generating. ```bash $ pgen example --out-dir models --clear ``` -------------------------------- ### Generate models and files with pgen Source: https://pg-generator.com/api-site Generates models, files, reports, and documentation from a PostgreSQL database. Requires database credentials and outputs to the specified directory, clearing it first. ```bash $ pgen example --outDir models --clear --database db --user user --password password ``` -------------------------------- ### composeWith (overload 1) Source: https://pg-generator.com/nav.02.api/classes/pggenerator Executes the default sub-generator `app` from a generator. If options are provided, they are combined with current options. ```APIDOC ## composeWith (overload 1) ### Description Executes the default sub-generator `app` from a generator. If options are provided, they are combined with current options. ### Method composeWith ### Signature `protected composeWith(generator: string, options?: GeneratorOptions): Promise` ### Parameters - **generator** (string) - Required - is the name or path of the generator. If it is a local path, use `require.resolve` or provide an absolute path. - **options?** (GeneratorOptions) - Optional - are the new options added on top of curent options. ### Returns _Promise_ ### Throws error if generator can not be found. ### Example this.composeWith("generator-from-npm"); this.composeWith("generator-from-npm", options); this.composeWith(require.resolve("./local-generator"), options); ### Defined in pg-generator.ts:232 ``` -------------------------------- ### process(destination, content) Source: https://pg-generator.com/nav.02.api/classes/pggenerator Writes generated content from render to the destination file. ```APIDOC ## process(destination, content) ### Description Writes generated content from render to the destination file. ### Method `Protected` `process` ### Parameters - **destination** (_string_) - Required - is the destionation path of the file to be cerated.. - **content** (_string_) - Required - is the content to process. ### Returns _any_ ### Defined in pg-generator.ts:153 ``` -------------------------------- ### generate() Source: https://pg-generator.com/nav.02.api/classes/pggenerator Renders all templates in the templates directory and writes generated contents to the output directory. Also copies files from the files directory. ```APIDOC ## generate() ### Description Renders all templates in `[rootDir]/templates` directory with the render function using related context data, and writes generated contents to the files in output directory. If render function returns `undefined` for a template/database object pair no file is not written for that pair. Template file names may contain variables and basic filter functions to change names of generated files. Additionally copies all files in `[rootDir]/files` to the output directory. ### Method `generate` ### Returns _Promise_ ### Defined in pg-generator.ts:49 ``` -------------------------------- ### Add custom filters to nunjucks Source: https://pg-generator.com/nav.03.creating-generators/05.filters.html Defines a custom filter 'hello' and adds it to a nunjucks environment. Demonstrates the pattern for adding custom filters. ```typescript import { join } from "path"; import nunjucks, { Environment } from "nunjucks"; const customFilters = { hello: (input) => `Hello! ${input}`, }; const environment = new nunjucks.FileSystemLoader(join(__dirname, "templates")); Object.entries(customFilters).forEach(([name, filter]) => environment.addFilter(name, filter)); ``` -------------------------------- ### Generator directory structure with sub-generators Source: https://pg-generator.com/nav.03.creating-generators Shows the folder layout for a generator with three sub-generators: app, md, and orm. The folder name determines the sub-generator name. ```text ├─ package.json └─ dist/ ├─ app/ ├─ md/ ├─ orm/ ``` -------------------------------- ### generate(generator, options?) Source: https://pg-generator.com/api-site/modules Executes the default sub-generator 'app' from a generator. This function is used to run a generator by name or path. ```APIDOC ## generate(generator: string, options?: Options): Promise ### Description Executes the default sub-generator `app` from a generator. ### Parameters - **generator** (string) - Required - The name or path of the generator. If it is a local path, use `require.resolve` or provide an absolute path. - **options** (Options) - Optional - The options for the generator. ### Returns Promise ### Example ``` generate("generator-from-npm", options); generate(require.resolve("./local-generator"), options); ``` ``` -------------------------------- ### scaffold(scaffoldName, __namedParameters) Source: https://pg-generator.com/api-site/modules Creates a skeleton Node.js project for a generator (pg-generator plugin). Throws an error if the required scaffold is unavailable or the output directory contains files. ```APIDOC ## scaffold(scaffoldName: string, __namedParameters: { name?: string; outDir: string }): Promise ### Description Creates a skeleton Node.js project for a generator (pg-generator plugin). ### Parameters - **scaffoldName** (string) - Required - The name to create scaffold from. - **__namedParameters** (object) - Required - **name** (string) - Optional - **outDir** (string) - Required ### Returns Promise ### Throws Error if required scaffold is unavailable or output directory contains files. ``` -------------------------------- ### composeWith Source: https://pg-generator.com/api-site/classes/pggenerator Executes a sub-generator from a generator, optionally with options or a sub-generator name. ```APIDOC ## composeWith ### Description Executes the default sub-generator `app` from a generator. If options are provided, they are combined with current options. Also can execute a specific sub-generator with options. ### Method composeWith ### Signatures - `composeWith(generator: string, options?: GeneratorOptions): Promise` - `composeWith(generator: string, subGeneratorName?: string, options?: GeneratorOptions): Promise` ### Parameters - **generator** (string) - Required - is the name or path of the generator. If it is a local path, use `require.resolve` or provide an absolute path. - **subGeneratorName** (string) - Optional - is the name of the sub-generator to be executed. - **options** (GeneratorOptions) - Optional - are the new options added on top of current options. ### Returns Promise ### Throws error if generator or sub-generator can not be found. ### Example ``` this.composeWith("generator-from-npm"); this.composeWith("generator-from-npm", options); this.composeWith(require.resolve("./local-generator"), options); this.composeWith("generator-from-npm", "sub-generator"); this.composeWith(require.resolve("./local-generator"), "sub-generator", options); ``` ``` -------------------------------- ### copyTemplate Source: https://pg-generator.com/api-site/classes/pggenerator Copies a source file to a destination, creating the destination directory if needed. ```APIDOC ## copyTemplate ### Description Copy the source file to the destination. Also creates the destination directory if it does not exist. ### Method copyTemplate ### Signature `copyTemplate(source: string, destination: string): Promise` ### Parameters - **source** (string) - Required - is the source file to copy. - **destination** (string) - Required - is the destination file to be created. ### Returns Promise ``` -------------------------------- ### fill Source: https://pg-generator.com/nav.02.api/modules/filterfunctions Completes given input's length using with given character (by default space). ```APIDOC ## fill(input?: string, length?: number, char?: string): string ### Description Completes given input's length using with given character (by default space). It may be used to align strings in JSDoc etc. ### Method fill ### Parameters - **input** (string) - Optional, default "" - is the input to complete length of. - **length** (number) - Optional, default 20 - is the length of the finel string. - **char** (string) - Optional, default " " - is the character to be used for filling. ### Returns string ### Example ``` completeWithChar("member", "10"); // "member " completeWithChar("member", "10", "-"); // "member----" ``` ``` -------------------------------- ### Template file src/app/templates/[table]{schema.name # dash-case}{name # dash-case}.md.njk Source: https://pg-generator.com/nav.03.creating-generators/01.getting-started.html Nunjucks template that generates a markdown table listing all columns of a table. It uses filters like dash-case and dboColumnTypeModifier, and conditionally displays primary key, foreign key, not null, and index count. ```nunjucks |PK|FK|Name|Type|NN|Index| |:-:|:-:|---|---|:-:|:-:| {%- for column in table.columns %} |{{ "🔑" if column.isPrimaryKey }}|{{ "FK" if column.isForeignKey }}|{{column.name}}|{{column.type.name}}{{ column | dboColumnTypeModifier }}|{{ "●" if column.notNull else "○" }}|{{ column.indexes.length if column.indexes.length > 0 }}| {%- endfor %} ``` -------------------------------- ### Set envPrefix to use environment variables Source: https://pg-generator.com/api-site/interfaces/clientoptions Sets the environment variable prefix to 'DB' so that pg-structure reads database client details from environment variables like DB_DATABASE, DB_USER, etc. ```javascript const config = { envPrefix: "DB" } ``` -------------------------------- ### context() Source: https://pg-generator.com/nav.03.creating-generators/03.generators.html Used to send custom context data to the templates. Return an object to merge into context. End-users may override these data using the contextFile option. ```APIDOC ## context() ### Description Used to send custom context data to the templates. Return an object to merge into context. End-users may override these data using the `contextFile` option. ### Method context() ### Parameters None ### Returns - **Record** - An object to merge into the context. ### Example ```typescript export default class App extends PgGenerator { protected context(): Record { return { global: { addSchemaName: true } }; } } ``` ### Notes - Context is the data passed to the templates as an object. pg-generator automatically passes related database object with a key equal to the database object type (e.g., `db`, `schema`, `table`, `view`, `function`). The key `o` is an alias to the database object. ``` -------------------------------- ### format Source: https://pg-generator.com/nav.02.api/classes/pggenerator Formats given content. By default `prettier` is used. Note that at this stage file is not written to disk yet. ```APIDOC ## format ### Description Formats given content. By default `prettier` is used. Plase note that at this stage file is not written to disk yet. ### Method format ### Signature `protected format(destination: string, content?: string): undefined | string | Promise` ### Parameters - **destination** (string) - Required - is the path of the destination file to be created. - **content?** (string) - Optional - is the content to format. ### Returns _undefined_ | _string_ | _Promise_ - formatted code. ### Defined in pg-generator.ts:142 ``` -------------------------------- ### clear() Source: https://pg-generator.com/nav.03.creating-generators/03.generators.html Called only when the 'clear' option is true. By default, it deletes the output directory. Override to customize the deletion operation. ```APIDOC ## clear() ### Description Called only when the `clear` option is true. By default, it deletes the output directory. Override to customize the deletion operation. ### Method clear() ### Parameters None ### Example ```typescript import { join } from "path"; import { del } from "del"; export default class App extends PgGenerator { protected async init(): Promise { await del(`${this.destinationPath()}/*.md`); } } ``` ### Notes - The example shows overriding `init` to delete only markdown files instead of the whole directory. ``` -------------------------------- ### format(destination, content) Source: https://pg-generator.com/nav.03.creating-generators/03.generators.html Called after content is rendered but before it is written to disk. By default, pg-generator formats the content using prettier. Override to change the default behavior. ```APIDOC ## format(destination, content) ### Description Called after content is rendered but before it is written to disk. By default, pg-generator formats the content using prettier. Override to change the default behavior. ### Method format(destination, content) ### Parameters - **destination** (string) - Required - The destination path where the content will be written. - **content** (string) - Optional - The rendered content to be formatted. ### Returns - **Promise | undefined | string** - The formatted content, or undefined if no formatting is needed. ### Example ```typescript export default class Md extends PgGenerator { protected format(destination: string, content?: string): Promise | undefined | string { return myFormatter.format(content); } } ``` ``` -------------------------------- ### generate(generator, subGenerator?, options?) Source: https://pg-generator.com/api-site/modules Executes a sub-generator from a generator. This overload allows specifying a sub-generator name. ```APIDOC ## generate(generator: string, subGenerator?: string, options?: Options): Promise ### Description Executes a sub-generator from a generator. ### Parameters - **generator** (string) - Required - The name or path of the generator. If it is a local path, use `require.resolve` or provide an absolute path. - **subGenerator** (string) - Optional - The name of the generator. - **options** (Options) - Optional - The new options added on top of current options. ### Returns Promise ### Example ``` generate("generator-from-npm", "sub-generator"); generate(require.resolve("./local-generator"), "sub-generator", options); ``` ``` -------------------------------- ### composeWith (overload 2) Source: https://pg-generator.com/nav.02.api/classes/pggenerator Executes a sub-generator from a generator. If options are provided, they are merged with current options. Some options are changed to sensible defaults for sub-generators. ```APIDOC ## composeWith (overload 2) ### Description Executes a sub-generator from a generator. If options are provided, they are merged with current options. Also some of the options are changed to sensible default values for sub-generators (e.g. `clear` is changed to `false`), but they can be overridden by newly provided options. ### Method composeWith ### Signature `protected composeWith(generator: string, subGeneratorName?: string, options?: GeneratorOptions): Promise` ### Parameters - **generator** (string) - Required - is the name or path of the generator. If it is a local path, use `require.resolve` or provide an absolute path. - **subGeneratorName?** (string) - Optional - is the name of the sub-generator to be executed. - **options?** (GeneratorOptions) - Optional - are the new options added on top of curent options. ### Returns _Promise_ ### Throws error if generator or sub-generator can not be found. ### Example this.composeWith("generator-from-npm", "sub-generator"); this.composeWith(require.resolve("./local-generator"), "sub-generator", options); ### Defined in pg-generator.ts:248 ``` -------------------------------- ### Run generator via API Source: https://pg-generator.com/nav.01.guide/01.getting-started Step 5 (API): Use the generate function from pg-generator to run the generator programmatically. The options object includes outDir and clear. ```javascript import { generate } from "pg-generator"; await generate("example", { outDir: "models", clear: true }); ``` -------------------------------- ### Context file: path/to/my-context.js Source: https://pg-generator.com/nav.01.guide/02.advanced.html JavaScript module exporting a context object. Here it sets global.addSchemaName to false, which controls whether PostgreSQL schema names are included in generated object names. ```javascript module.exports = { global: { addSchemaName: false, }, }; ```