### Install SQLCommenter Go Package Source: https://google.github.io/sqlcommenter/go/database_sql Use go get to install the SQLCommenter database/sql package. ```bash go get -u github.com/google/sqlcommenter/go/database/sql ``` -------------------------------- ### Install Gorilla Mux SQLCommenter Middleware Source: https://google.github.io/sqlcommenter/tags/gorrila Install the library using go get. This command fetches the latest version of the middleware. ```bash go get -u github.com/google/sqlcommenter/go/gorrila/mux ``` -------------------------------- ### Install Go Gorilla Mux SQLCommenter Source: https://google.github.io/sqlcommenter/go/gorrila_mux Install the SQLCommenter middleware for Gorilla Mux using go get. ```go go get -u github.com/google/sqlcommenter/go/gorrila/mux ``` -------------------------------- ### Install Go HTTP Tags Package Source: https://google.github.io/sqlcommenter/go/net_http Install the SQLCommenter Go HTTP tags package using go get. ```bash go get -u github.com/google/sqlcommenter/go/net/http ``` -------------------------------- ### Install google-cloud-sqlcommenter from source Source: https://google.github.io/sqlcommenter/python/django Clone the SQLCommenter repository and install from source. ```bash git clone https://github.com/google/sqlcommenter.git cd python/sqlcommenter-python && python3 setup.py install ``` -------------------------------- ### Start Rails Server Source: https://google.github.io/sqlcommenter/ruby/rails Start the Rails development server to observe the SQL comments in the logs. ```bash bin/rails s ``` -------------------------------- ### Node.js Application Start Source: https://google.github.io/sqlcommenter/node/sequelize Starts a Node.js application server listening on a specified port. ```javascript app.listen(port, () => console.log(`Application listening on ${port}`)); ``` -------------------------------- ### Install sqlcommenter-nodejs Package Source: https://google.github.io/sqlcommenter/node Install a specific sqlcommenter-nodejs package (e.g., knex) from the cloned repository using npm. Replace `` with the actual path to the package directory. ```bash npm install /path/to/sqlcommenter-nodejs/packages/knex ``` -------------------------------- ### Verify SQLCommenter Java Installation Source: https://google.github.io/sqlcommenter/java After installation, check for the expected directory structure in your local Maven repository. This confirms the build artifacts are correctly placed. ```bash ~/.m2/repository/io └── com    └── google    └── cloud    └── sqlcommenter    ├── 0.0.1    │   ├── sqlcommenter-java-0.0.1-javadoc.jar    │   ├── sqlcommenter-java-0.0.1-javadoc.jar.asc    │   ├── sqlcommenter-java-0.0.1-sources.jar    │   ├── sqlcommenter-java-0.0.1-sources.jar.asc    │   ├── sqlcommenter-java-0.0.1.jar    │   ├── sqlcommenter-java-0.0.1.jar.asc    │   └── sqlcommenter-java-0.0.1.pom    └── maven-metadata-local.xml ``` -------------------------------- ### Install google-cloud-sqlcommenter using pip Source: https://google.github.io/sqlcommenter/python/django Install the SQLCommenter package using pip for Django projects. ```bash pip3 install google-cloud-sqlcommenter ``` -------------------------------- ### Install SQLCommenter for Knex.js Source: https://google.github.io/sqlcommenter/node/knex Add the SQLCommenter Knex.js package as a dependency to your project's package.json file and run npm install. ```json { "@google-cloud/sqlcommenter-knex": "*" } ``` ```bash npm install @google-cloud/sqlcommenter-knex --save ``` -------------------------------- ### Example SQL Commenter Output Source: https://google.github.io/sqlcommenter/spec This is an example of a SQL statement augmented with a comment containing serialized key-value pairs. ```sql SELECT * FROM FOO /*action='%2Fparam*d',controller='index,'framework='spring', traceparent='00-5bd66ef5095369c7b0d1f8f4bd33716a-c532cb4098ac3dd2-01', tracestate='congo%3Dt61rcWkgMzE%2Crojo%3D00f067aa0ba902b7'*/ ``` -------------------------------- ### Run Laravel Development Server Source: https://google.github.io/sqlcommenter/php/laravel Start the Laravel development server from the command line to serve your application. ```bash php artisan serve ``` -------------------------------- ### Verify sqlcommenter-nodejs Installation Source: https://google.github.io/sqlcommenter/node Verify the installation of a specific sqlcommenter-nodejs package by running `npm list `. This command shows details of the installed package and its location. ```bash npm list @google-cloud/sqlcommenter-knex ``` -------------------------------- ### Build SQLCommenter Java from Source Source: https://google.github.io/sqlcommenter/java Run this command in the `java/sqlcommenter-java` directory to build the project from source. Ensure you have Gradle installed. ```bash $ ./gradlew install ``` -------------------------------- ### Key-Value Pair Serialization Example Source: https://google.github.io/sqlcommenter/spec Demonstrates the final serialization of a key-value pair. ```markdown key value pair | serialized_key | serialized_value | Final ---|---|---|--- `route=/polls 1000` | `route` | `'%2Fpolls%201000'` | `route='%2Fpolls%201000'` `name='DROP TABLE FOO'` | `route` | `'%2Fpolls%201000'` | `route='%2Fpolls%201000'` `name''="DROP TABLE USERS'"` | name='' | DROP%20TABLE%20USERS' | name=''=‘DROP%20TABLE%20USERS'’ ``` -------------------------------- ### Run Django Development Server Source: https://google.github.io/sqlcommenter/python/django Command to start the Django development server from the command line. ```bash python manage.py runserver ``` -------------------------------- ### Value Serialization Example Table Source: https://google.github.io/sqlcommenter/spec Illustrates the value serialization process with different inputs. ```markdown value | url_encode(value) | sql_escape_with_single_quotes ---|---|--- `DROP TABLE FOO` | `DROP%20TABLE%20FOO` | `'DROP%20TABLE%20FOO'` `/param first` | `%2Fparam%20first` | `'%2Fparam%20first'` `1234` | `1234` | `'1234'` ``` -------------------------------- ### Install SQLCommenter Laravel via Composer with Local Path Source: https://google.github.io/sqlcommenter/php/laravel Install the SQLCommenter Laravel package using Composer after configuring a local path repository. ```bash composer require "google/sqlcommenter-laravel" ``` -------------------------------- ### Basic Gorilla Mux Setup with SQLCommenter Source: https://google.github.io/sqlcommenter/go/gorrila_mux Use SQLCommenterMiddleware with a Gorilla Mux router to add SQLCommenter tags to requests. Ensure the router is used for handling HTTP requests. ```go import ( "net/http" sqlcommentermux "github.com/google/sqlcommenter/go/gorrila/mux" "github.com/gorilla/mux" ) func runApp() { r := mux.NewRouter() r.Use(sqlcommentermux.SQLCommenterMiddleware) r.HandleFunc("/", ActionHome).Methods("GET") http.ListenAndServe(":8081", r) } ``` -------------------------------- ### Install SQLCommenter for Sequelize Source: https://google.github.io/sqlcommenter/node/sequelize Add the SQLCommenter Sequelize package as a dependency to your project's package.json file and run npm install. ```json { "@google-cloud/sqlcommenter-sequelize": "*" } ``` ```bash npm install @google-cloud/sqlcommenter-sequelize --save ``` -------------------------------- ### Psycopg2 Example Output Source: https://google.github.io/sqlcommenter/python/psycopg2 Demonstrates the typical output when running a psycopg2 script with SQL Commenter enabled, showing fetched data. ```python python3 main.py (1, 'Wassup?', datetime.datetime(2019, 5, 30, 13, 51, 12, 910545, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))) (2, 'Wassup?', datetime.datetime(2019, 5, 30, 13, 57, 45, 905771, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))) (3, 'Wassup?', datetime.datetime(2019, 5, 30, 13, 57, 46, 908185, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))) (4, 'Wassup?', datetime.datetime(2019, 5, 30, 13, 57, 47, 557196, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))) (5, 'Wassup?', datetime.datetime(2019, 5, 30, 13, 57, 47, 853424, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))) ``` -------------------------------- ### Run Node.js Application Source: https://google.github.io/sqlcommenter/node/knex Execute the Node.js application using the `node` command. This will start the server and log a message indicating the application is listening on the specified port. ```bash $ node app.js Application listening on 3000 ``` -------------------------------- ### GET /posts SQL Query with Comments Source: https://google.github.io/sqlcommenter/ruby/rails Example of a SQL query generated by `GET /posts` endpoint, including `sqlcommenter_rails` fields. ```sql Post Load (0.1ms) SELECT "posts".* FROM "posts" /* action='index',application='SqlcommenterRailsDemo',controller='posts', db_driver='ActiveRecord::ConnectionAdapters::SQLite3Adapter', framework='rails_v6.0.0.rc1',route='/posts', traceparent='00-ff19308b1f17fedc5864e929bed1f44e-6ddace73a9debf63-01'*/ ``` -------------------------------- ### Example SQL Statements with Comments Source: https://google.github.io/sqlcommenter/java/hibernate These are example SQL statements generated during the unit test execution. They show how SQL Commenter appends contextual information like action, controller, and framework to the SQL queries. ```sql select tag0_.id as id1_2_, tag0_.name as name2_2_ from tag tag0_ where tag0_.name in (? , ?) /*action='CreatePost',controller='ForumController',framework='spring'*/ ``` ```sql call next value for hibernate_sequence /*action='CreatePost',controller='ForumController',framework='spring'*/ ``` ```sql insert into post (title, id) values (?, ?) /*action='CreatePost',controller='ForumController',framework='spring'*/ ``` ```sql insert into post_tag (post_id, tag_id) values (?, ?) /*action='CreatePost',controller='ForumController',framework='spring'*/ ``` ```sql insert into post_tag (post_id, tag_id) values (?, ?) /*action='CreatePost',controller='ForumController',framework='spring'*/ ``` ```sql select post0_.id as id1_0_, post0_.title as title2_0_ from post post0_ where post0_.title=? /*action='FindPostsByTitle',controller='ForumController',framework='spring'*/ ``` ```sql select post0_.id as id1_0_0_, post0_.title as title2_0_0_ from post post0_ where post0_.id=? /*action='FindPostById',controller='ForumController',framework='spring'*/ ``` -------------------------------- ### Default Django urls.py for SQLCommenter Source: https://google.github.io/sqlcommenter/python/django Example urls.py configuration for a Django app. ```python # polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] ``` -------------------------------- ### Gorilla Mux Setup with SQLCommenter and OpenTelemetry Source: https://google.github.io/sqlcommenter/go/gorrila_mux Integrate SQLCommenterMiddleware with otelmux.Middleware for Gorilla Mux to include OpenTelemetry traceparent information in SQL comments. This requires setting up an OpenTelemetry tracer provider. ```go import ( "context" "log" "net/http" sqlcommentermux "github.com/google/sqlcommenter/go/gorrila/mux" "github.com/gorilla/mux" "go.opentelemetry.io/contrib/instrumentation/github.com/gorilla/mux/otelmux" "go.opentelemetry.io/otel" stdout "go.opentelemetry.io/otel/exporters/stdout/stdouttrace" "go.opentelemetry.io/otel/propagation" sdktrace "go.opentelemetry.io/otel/sdk/trace" ) func main() { tp, err := initTracer() if err != nil { log.Fatal(err) } defer func() { if err := tp.Shutdown(context.Background()); err != nil { log.Printf("Error shutting down tracer provider: %v", err) } }() r := mux.NewRouter() r.Use(otelmux.Middleware("sqlcommenter sample-server"), sqlcommentermux.SQLCommenterMiddleware) r.HandleFunc("/", ActionHome).Methods("GET") http.ListenAndServe(":8081", r) } func initTracer() (*sdktrace.TracerProvider, error) { exporter, err := stdout.New(stdout.WithPrettyPrint()) if err != nil { return nil, err } tp := sdktrace.NewTracerProvider( sdktrace.WithSampler(sdktrace.AlwaysSample()), sdktrace.WithBatcher(exporter), ) otel.SetTracerProvider(tp) otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{})) return tp, nil } ``` -------------------------------- ### Configure Composer for Local Path Installation Source: https://google.github.io/sqlcommenter/php/laravel Add a local path repository to your composer.json file to install the SQLCommenter Laravel package from a cloned source. ```json # Add the following to composer.json "repositories": [ { "type": "path", "url": "/full/or/relative/path/to/sqlcommenter/php/sqlcommenter-php/packages/sqlcommenter-laravel/" } ] ``` -------------------------------- ### Default Django views.py for SQLCommenter Source: https://google.github.io/sqlcommenter/python/django Example views.py for a Django app to demonstrate SQLCommenter integration. ```python # polls/views.py from django.http import HttpResponse from .models import Question def index(request): count = Question.objects.count() return HttpResponse(f"There are {count} questions in the DB.\n") ``` -------------------------------- ### End-to-End Example with psycopg2 Source: https://google.github.io/sqlcommenter/python/flask Demonstrates a full Flask application using psycopg2 with SQLCommenter. It sets up a database connection with a custom cursor factory and runs a Flask app that queries a database. The database logs will show SQL statements augmented with comments. ```python #!/usr/bin/env python3 import psycopg2 import json import flask app = flask.Flask(__name__) from google.cloud.sqlcommenter import FlaskMiddleware from google.cloud.sqlcommenter.psycopg2.extension import CommenterCursorFactory conn = None @app.route('/polls') def get_polls(): cursor = conn.cursor() cursor.execute("SELECT * FROM polls_question") str_polls = list(map(lambda s: str(s), cursor)) cursor.close() return json.dumps(str_polls) def main(): global conn try: conn = psycopg2.connect(user='', password='$postgres$', host='127.0.0.1', port='5432', database='quickstart_py', cursor_factory=CommenterCursorFactory()) # Now enable the middleware. FlaskMiddleware(app) # Finally run the Flask web app. app.run(host='localhost', port=8088, threaded=True) except Exception as e: print('Encountered exception %s'%(e)) finally: if conn: conn.close() if __name__ == '__main__': main() ``` ```sql SELECT * FROM polls_question /*controller='get_polls',db_driver='psycopg2',framework='sqlalchemy%3A1.3.4', route='/polls',traceparent='00-5b3df77064f35f091e89fb40022e2a1d-9bbd4868cf0ba2c3-01'*/ ``` -------------------------------- ### Define Django URL Patterns Source: https://google.github.io/sqlcommenter/python/django Set up basic URL routing for a Django app. This example shows how to map the root URL to the index view. ```python from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] ``` -------------------------------- ### Example PostgreSQL Log Output with SQL Statements Source: https://google.github.io/sqlcommenter/databases/postgresql This is an example of the log output generated by a PostgreSQL server configured for detailed logging. It shows connection information and executed SQL statements, including those with SQL Commenter tags. ```log 2019-05-31 16:27:27.482 PDT [19175] LOG: listening on IPv4 address "127.0.0.1", port 5432 2019-05-31 16:27:27.482 PDT [19175] LOG: listening on IPv6 address "::1", port 5432 2019-05-31 16:27:27.482 PDT [19175] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432" 2019-05-31 16:27:27.503 PDT [19176] LOG: database system was shut down at 2019-05-31 16:27:06 PDT 2019-05-31 16:27:27.508 PDT [19175] LOG: database system is ready to accept connections 2019-05-31 16:27:31.190 PDT [19183] LOG: statement: SET TIME ZONE 'UTC' 2019-05-31 16:27:31.195 PDT [19183] LOG: statement: INSERT INTO "polls_question" ("question_text", "pub_date") VALUES ('Wassup?', '2019-05-31T23:27:31.175952+00:00'::timestamptz) RETURNING "polls_question"."id" /*controller='index',db_driver='django.db.backends.postgresql', framework='django%3A2.2.1',route='%5Epolls/%24'*/ ``` -------------------------------- ### Postgresql Log with DB Framework Info Source: https://google.github.io/sqlcommenter/python/sqlalchemy Example of a Postgresql server log showing a SQL statement with database framework information appended by SQLCommenter. ```sql 2019-07-18 14:11:19.576 -03 [30108] LOG: statement: SELECT * FROM polls_question /*db_framework='sqlalchemy%3A1.3.5'*/ ``` -------------------------------- ### Postgresql Log with DB Driver Info Source: https://google.github.io/sqlcommenter/python/sqlalchemy Example of a Postgresql server log showing a SQL statement with database driver information appended by SQLCommenter. ```sql 2019-07-18 14:03:33.426 -03 [29858] LOG: statement: SELECT * FROM polls_question /*db_driver='psycopg2'*/ ``` -------------------------------- ### Run PostgreSQL Server with Custom Data Directory Source: https://google.github.io/sqlcommenter/databases/postgresql Start the PostgreSQL server using the `postgres` command, specifying the `PGDATA` environment variable to use a custom data directory. This is often done after modifying configuration files. ```bash $ PGDATA=/usr/local/var/postgres postgres ``` -------------------------------- ### Postgresql Log with OpenCensus Trace Source: https://google.github.io/sqlcommenter/python/sqlalchemy Example of a Postgresql server log showing a SQL statement with OpenCensus trace information appended by SQLCommenter. ```sql 2019-07-18 14:10:15.228 -03 [30071] LOG: statement: SELECT * FROM polls_question /*traceparent='00-bf66750ad4c76f614c0a99d843758cbb-e6b27c3caf35de73-01'*/ ``` -------------------------------- ### All SQL Commenter Fields in SQL Comments Source: https://google.github.io/sqlcommenter/node/sequelize A comprehensive example showing all available SQL Commenter fields, including traceparent, tracestate, route, client_timezone, and db_driver. ```sql 2019-06-03 14:32:10.842 PDT [32004] LOG: statement: SELECT * from polls_question /*client_timezone:'%2B00%3A00',db_driver='sequelize%3A0.0.1',route='%5E%2Fpolls%2F%1000',traceparent='00-11000000000000ff-020000ee-01',tracestate='brazzaville=t61rcWkgMzE,rondo=00f067aa0ba902b7'*/ ``` -------------------------------- ### PostgreSQL Log with Controller and Framework Comments Source: https://google.github.io/sqlcommenter/python/django Example of a PostgreSQL log statement showing SQL comments added by SQL Commenter, including controller and framework information. ```sql 2019-07-19 14:27:51.370 -03 [41382] LOG: statement: SELECT COUNT(*) AS "__count" FROM "polls_question" /*controller='index',framework='django%3A2.2.3',route='polls/'*/ ``` -------------------------------- ### SQLAlchemy Query Output Source: https://google.github.io/sqlcommenter/python/sqlalchemy Example output from a SQLAlchemy query executed with SQLCommenter. ```text python3 main.py (1, 'Wassup?', datetime.datetime(2019, 5, 30, 13, 51, 12, 910545, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))) (2, 'Wassup?', datetime.datetime(2019, 5, 30, 13, 57, 45, 905771, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))) (3, 'Wassup?', datetime.datetime(2019, 5, 30, 13, 57, 46, 908185, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))) (4, 'Wassup?', datetime.datetime(2019, 5, 30, 13, 57, 47, 557196, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))) (5, 'Wassup?', datetime.datetime(2019, 5, 30, 13, 57, 47, 853424, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=-420, name=None))) ``` -------------------------------- ### Node.js Sequelize with All Options Set Source: https://google.github.io/sqlcommenter/node/sequelize Demonstrates a comprehensive SQLCommenter configuration for Node.js Sequelize applications, enabling client timezone, database driver, route, traceparent, and tracestate information in SQL comments. This setup provides maximum observability. ```javascript // In file app.js. const { NodeTracerProvider } = require("@opentelemetry/node"); const { BatchSpanProcessor } = require("@opentelemetry/tracing"); const { TraceExporter, } = require("@google-cloud/opentelemetry-cloud-trace-exporter"); const tracerProvider = new NodeTracerProvider(); // Export to Google Cloud Trace tracerProvider.addSpanProcessor( new BatchSpanProcessor(new TraceExporter({ logger }), { bufferSize: 500, bufferTimeout: 5 * 1000, }) ); tracerProvider.register(); // OpenTelemetry initialization should happen before importing any libraries // that it instruments const { Sequelize } = require("sequelize"); const { wrapSequelizeAsMiddleware, } = require("@google-cloud/sqlcommenter-sequelize"); const sequelize = new Sequelize("postgres://user:pass@example.com:5432/dbname"); const express = require("express"); const app = express(); const port = process.env.APP_PORT || 3000; // SQLCommenter express middleware injects the route into the traces app.use( wrapSequelizeAsMiddleware( sequelize, { client_timezone: true, db_driver: true, route: true, traceparent: true, tracestate: true, }, { TraceProvider: "OpenTelemetry" } ) ); app.get("/", (req, res) => res.send("Hello, sqlcommenter-nodejs!!")); app.get("^/polls/:param", function (req, res) { sequelize ``` -------------------------------- ### Install SQLCommenter Laravel via Composer Source: https://google.github.io/sqlcommenter/php/laravel Use Composer to add the SQLCommenter Laravel package to your project dependencies. ```bash composer require google/sqlcommenter-laravel ``` -------------------------------- ### End-to-End Example with SQLAlchemy Source: https://google.github.io/sqlcommenter/python/flask Illustrates a Flask application using SQLAlchemy with SQLCommenter. It configures SQLAlchemy's create_engine and registers an event listener for before cursor execution. Visiting a route triggers a query, and database logs will show the query with added comments. ```python #!/usr/bin/env python3 import json import flask app = flask.Flask(__name__) from sqlalchemy import create_engine, event from sqlcommenter import FlaskMiddleware from sqlcommenter.sqlalchemy.executor import BeforeExecuteFactory engine = None @app.route('/polls') def get_polls(): result_proxy = engine.execute("SELECT * FROM polls_question") str_polls = list(map(lambda s: str(s), result_proxy)) result_proxy.close() return json.dumps(str_polls) def main(): global engine engine = create_engine("postgresql://:$postgres$@127.0.0.1:5432/quickstart_py") event.listen(engine, 'before_cursor_execute', BeforeExecuteFactory(), retval=True) FlaskMiddleware(app) app.run(host='localhost', port=8089, threaded=True) if __name__ == '__main__': main() ``` ```sql SELECT * FROM polls_question /*controller='get_polls',db_driver='psycopg2%3A2.8.2%20%28dt%20dec%20pq3%20ext%20lo64%29', dbapi_level='2.0',dbapi_threadsafety=2,driver_paramstyle='pyformat', framework='flask%3A1.0.3',libpq_version=100001,route='/polls'*/ ``` -------------------------------- ### Django urls.py to include App Name in SQLCommenter Source: https://google.github.io/sqlcommenter/python/django Example urls.py configuration for a Django app when including app name in SQLCommenter. ```python # polls/urls.py from django.urls import path from . import apps, views app_name = apps.PollsConfig.name urlpatterns = [ path('', views.index, name='index'), ] ``` -------------------------------- ### Knex Integration with Route Tracing Source: https://google.github.io/sqlcommenter/node/knex Integrate Knex.js with SQLCommenter to include route information in traces. This setup is suitable for Express.js applications. ```javascript // In file app.js. const Knex = require('knex'); // Knex to be wrapped say v0.0.1 const {wrapMainKnexAsMiddleware} = require('@google-cloud/sqlcommenter-knex'); const express = require('express'); const options = { client: 'postgresql', connection: { host: '127.0.0.1', password: '$postgres$', database: 'quickstart_nodejs' } }; const knex = Knex(options); // knex instance const app = express(); const port = process.env.APP_PORT || 3000; // Use the knex+express middleware with route app.use(wrapMainKnexAsMiddleware(Knex, {route: true})); app.get('/', (req, res) => res.send('Hello, sqlcommenter-nodejs!!')); app.get('^/polls/:param', function(req, res) { knex.raw('SELECT * from polls_question').then(function(polls) { const blob = JSON.stringify(polls); res.send(blob); }).catch(function(err) { console.log(err); res.send(500); }); }); app.listen(port, () => console.log(`Application listening on ${port}`)); ``` -------------------------------- ### Prepare SQLCommenter Tags from HTTP Request (Go) Source: https://google.github.io/sqlcommenter/tags/go Use this low-level package to prepare SQLCommenterTags from an HTTP request. The core package can then be used to inject these tags into a context. ```go import ( sqlcommenterhttp "github.com/google/sqlcommenter/go/net/http" core "github.com/google/sqlcommenter/go/core" ) requestTags := sqlcommenterhttp.NewHTTPRequestTags(framework string, route string, action string) ctx := core.ContextInject(request.Context(), requestTags) requestWithTags := request.WithContext(ctx) ``` -------------------------------- ### Prepare and Inject HTTP Request Tags Source: https://google.github.io/sqlcommenter/tags/context Use this to create SQLCommenterTags from an HTTP request and inject them into the request context. Ensure the core package is imported for context injection. ```go import ( sqlcommenterhttp "github.com/google/sqlcommenter/go/net/http" "github.com/google/sqlcommenter/go/core" ) requestTags := sqlcommenterhttp.NewHTTPRequestTags(framework string, route string, action string) ctx := core.ContextInject(request.Context(), requestTags) requestWithTags := request.WithContext(ctx) ``` -------------------------------- ### SQL Query with All Options Set Source: https://google.github.io/sqlcommenter/node/knex This log demonstrates a SQL query with all available SQL Commenter options enabled: db_driver, route, traceparent, and tracestate. This provides comprehensive context for the query. ```sql 2019-06-03 14:32:10.842 PDT [32004] LOG: statement: SELECT * from polls_question /*db_driver='knex%3A0.0.1',route='%5E%2Fpolls%2F%1000',traceparent='00-11000000000000ff-020000ee-01',tracestate='brazzaville=t61rcWkgMzE,rondo=00f067aa0ba902b7'*/ ``` -------------------------------- ### PostgreSQL Log with Traceparent Comment Source: https://google.github.io/sqlcommenter/python/django Example of a PostgreSQL log statement with a traceparent comment, typically used for distributed tracing. ```sql 2019-07-19 17:39:27.430 -03 [46170] LOG: statement: SELECT COUNT(*) AS "__count" FROM "polls_question" /*traceparent='00-fd720cffceba94bbf75940ff3caaf3cc-4fd1a2bdacf56388-01'*/ ``` -------------------------------- ### Implement Posts Controller Actions Source: https://google.github.io/sqlcommenter/ruby/rails Define the `index` and `create` actions for the `PostsController` to handle fetching and creating posts. ```ruby # app/controllers/posts_controller.rb class PostsController < ApplicationController def index render json: Post.all end def create title = params[:title].to_s.strip head :bad_request if title.empty? render json: Post.create!(title: title) end end ``` -------------------------------- ### POST /posts SQL Query with Comments Source: https://google.github.io/sqlcommenter/ruby/rails Example of a SQL query generated by `POST /posts` endpoint, including `sqlcommenter_rails` fields. ```sql Post Create (0.2ms) INSERT INTO "posts" ("title", "created_at", "updated_at") VALUES (?, ?, ?) /*action='create',application='SqlcommenterRailsDemo', controller='posts',db_driver='ActiveRecord::ConnectionAdapters::SQLite3Adapter', framework='rails_v6.0.0.rc1',route='/posts', traceparent='00-ff19308b1f17fedc5864e929bed1f44e-6ddace73a9debf63-01'*/ ``` -------------------------------- ### PostgreSQL Log with DB Driver Comment Source: https://google.github.io/sqlcommenter/python/django Example of a PostgreSQL log statement with a db_driver comment, indicating the database backend used by the application. ```sql 2019-07-19 14:47:53.066 -03 [41602] LOG: statement: SELECT COUNT(*) AS "__count" FROM "polls_question" /*db_driver='django.db.backends.postgresql'*/ ``` -------------------------------- ### PostgreSQL Log with App Name Comment Source: https://google.github.io/sqlcommenter/python/django Example of a PostgreSQL log statement showing an app_name comment, useful for identifying the application generating the query. ```sql 2019-07-19 15:31:33.681 -03 [42962] LOG: statement: SELECT COUNT(*) AS "__count" FROM "polls_question" /*app_name='polls'*/ ``` -------------------------------- ### Configure SQLCommenter with All Fields Source: https://google.github.io/sqlcommenter/node/knex Manually set all available fields (db_driver, route, traceparent, tracestate) and specify OpenTelemetry as the trace provider for comprehensive SQL comments. ```javascript // Manually set all the variables. wrapMainKnexAsMiddleware( Knex, include={ db_driver: true, route: true, traceparent: true, tracestate: true, }, options={ TraceProvider: 'OpenTelemetry' } ); ``` -------------------------------- ### psycopg2 Log with libpq Version Source: https://google.github.io/sqlcommenter/python/psycopg2 Demonstrates a PostgreSQL server log entry for a SQL statement including the libpq version comment added by SQL Commenter. ```sql 2019-07-17 16:05:37.618 -03 [16708] LOG: statement: SELECT * FROM polls_question /*libpq_version=110002*/ ``` -------------------------------- ### Configure Hibernate Transaction Template Source: https://google.github.io/sqlcommenter/java/hibernate Sets up a TransactionTemplate for Hibernate, requiring a SessionFactory and a transaction manager. This is a common setup for managing transactions in Spring applications using Hibernate. ```java public TransactionTemplate transactionTemplate(SessionFactory sessionFactory) { return new TransactionTemplate(transactionManager(sessionFactory)); } ``` -------------------------------- ### Prepare and Inject SQLCommenter Tags Source: https://google.github.io/sqlcommenter/go/net_http Use the http-tags package to create SQLCommenterTags from an HTTP request and inject them into the request context. This is useful for instrumenting various frameworks. ```go import ( sqlcommenterhttp "github.com/google/sqlcommenter/go/net/http" "github.com/google/sqlcommenter/go/core" ) requestTags := sqlcommenterhttp.NewHTTPRequestTags(framework string, route string, action string) ctx := core.ContextInject(request.Context(), requestTags) requestWithTags := request.WithContext(ctx) ``` -------------------------------- ### Make HTTP Request with curl Source: https://google.github.io/sqlcommenter/python/django Use curl to send an HTTP GET request to the Django development server. This action will generate a SQL query that SQL Commenter can annotate. ```bash curl http://127.0.0.1:8000/polls/ ``` -------------------------------- ### Knex Integration with OpenTelemetry and All Options Source: https://google.github.io/sqlcommenter/node/knex Configure Knex.js with OpenTelemetry and SQLCommenter, enabling traceparent, tracestate, and db_driver. Ensure OpenTelemetry initialization precedes library imports. ```javascript // In file app.js. const { NodeTracerProvider } = require("@opentelemetry/node"); const { BatchSpanProcessor } = require("@opentelemetry/tracing"); const { TraceExporter, } = require("@google-cloud/opentelemetry-cloud-trace-exporter"); const tracerProvider = new NodeTracerProvider(); // Export to Google Cloud Trace tracerProvider.addSpanProcessor( new BatchSpanProcessor(new TraceExporter({ logger }), { bufferSize: 500, bufferTimeout: 5 * 1000, }) ); tracerProvider.register(); // OpenTelemetry initialization should happen before importing any libraries // that it instruments const express = require("express"); const Knex = require("knex"); const { wrapMainKnexAsMiddleware } = require("@google-cloud/sqlcommenter-knex"); const knexOptions = { client: 'postgresql', connection: { host: '127.0.0.1', password: '$postgres$', database: 'quickstart_nodejs' } }; const knex = Knex(knexOptions); // knex instance const app = express(); const port = process.env.APP_PORT || 3000; // SQLCommenter express middleware injects the route into the traces app.use( wrapMainKnexAsMiddleware( Knex, { traceparent: true, tracestate: true, // Optional db_driver: false, route: false, }, { TraceProvider: "OpenTelemetry" } ) ); app.get('/', (req, res) => res.send('Hello, sqlcommenter-nodejs!!')); app.get('^/polls/:param', function(req, res) { knex.raw('SELECT * from polls_question').then(function(polls) { const blob = JSON.stringify(polls); res.send(blob); }).catch(function(err) { console.log(err); res.send(500); }); }); app.listen(port, () => console.log(`Application listening on ${port}`)); ``` -------------------------------- ### Node.js Sequelize with Route Source: https://google.github.io/sqlcommenter/node/sequelize Applies SQLCommenter middleware to an Express.js application using Sequelize, enabling the injection of route information into SQL query comments. This setup is suitable for basic route tracking. ```javascript // In file app.js. const Sequelize = require('sequelize'); const {wrapSequelizeAsMiddleware} = require('@google-cloud/sqlcommenter-sequelize'); const express = require('express'); // Using a connection URI const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname'); const app = express(); const port = process.env.APP_PORT || 3000; // Use the sequelize+express middleware with route app.use(wrapSequelizeAsMiddleware(sequelize, {route: true})); app.get('/', (req, res) => res.send('Hello, sqlcommenter-nodejs!!')); app.get('^/polls/:param', function(req, res) { sequelize.query('SELECT * from polls_question').then(function(polls) { const blob = JSON.stringify(polls); res.send(blob); }).catch(function(err) { console.log(err); res.send(500); }); }); app.listen(port, () => console.log(`Application listening on ${port}`)); ``` -------------------------------- ### SQLCommenter Middleware for Gorilla Mux (Go) Source: https://google.github.io/sqlcommenter/tags/go This library provides a middleware that extracts SQLCommenter HTTP request tags from a request being handled by gorilla/mux and attaches them to the request’s context. This same context, when used to run queries using sqlcommenter/go/database/sql, allows request tags and traceparent(if using otelmux) to be passed into SQL comments. ```go import ( "net/http" sqlcommentermux "github.com/google/sqlcommenter/go/gorrila/mux" "github.com/gorilla/mux" ) func runApp() { r := mux.NewRouter() r.Use(sqlcommentermux.SQLCommenterMiddleware) r.HandleFunc("/", ActionHome).Methods("GET") http. ``` -------------------------------- ### Configure Gorilla Mux with SQLCommenter Middleware Source: https://google.github.io/sqlcommenter/tags/mux Use the SQLCommenterMiddleware in your Gorilla Mux router to automatically process incoming requests. ```go import ( "net/http" sqlcommentermux "github.com/google/sqlcommenter/go/gorrila/mux" "github.com/gorilla/mux" ) func runApp() { r := mux.NewRouter() r.Use(sqlcommentermux.SQLCommenterMiddleware) r.HandleFunc("/", ActionHome).Methods("GET") http. ``` -------------------------------- ### Hibernate Test Setup with Transactional Data Initialization Source: https://google.github.io/sqlcommenter/java/hibernate Initializes test data within a transaction using Spring's TransactionTemplate. This ensures that the test environment is set up with necessary entities before test execution. ```java @Before public void init() { try { transactionTemplate.execute((TransactionCallback) transactionStatus -> { Tag hibernate = new Tag(); hibernate.setName("hibernate"); entityManager.persist(hibernate); Tag jpa = new Tag(); jpa.setName("jpa"); entityManager.persist(jpa); return null; }); } catch (TransactionException e) { fail(e.getMessage()); } } ``` -------------------------------- ### Run SQLCommenter Java Tests Source: https://google.github.io/sqlcommenter/java Execute the test suite for the sqlcommenter-java project using Gradle. This command verifies the functionality of the library. ```bash $ ./gradlew test ``` -------------------------------- ### psycopg2 Log with DB Driver Info Source: https://google.github.io/sqlcommenter/python/psycopg2 Illustrates a PostgreSQL server log entry for a SQL statement including the database driver information, such as version and build details, appended by SQL Commenter. ```sql 2019-07-17 15:56:05.192 -03 [16491] LOG: statement: SELECT * FROM polls_question /*db_driver='psycopg2%3A2.8.3%20%28dt%20dec%20pq3%20ext%20lo64%29'*/ ``` -------------------------------- ### Monitor Development Log for SQL Statements Source: https://google.github.io/sqlcommenter/ruby/rails Use `tail` and `grep` to monitor the server's development log for SQL statements generated by the application. ```bash tail -f log/development.log | grep 'Post ' ``` -------------------------------- ### Use Local Maven Packages Source: https://google.github.io/sqlcommenter/java When using Maven to build packages that depend on locally installed artifacts (like SQLCommenter Java), use this command to ensure Maven can find them. The `-nsu` flag prevents Maven from checking remote repositories for snapshots. ```bash mvn install -nsu ``` -------------------------------- ### Open Database Connection with SQLCommenter Source: https://google.github.io/sqlcommenter/go/database_sql Use the sqlcommenter's go-sql database driver to open a connection. It's recommended to use context-based methods like QueryContext for passing information from the framework to the database driver. ```go import ( "database/sql" gosql "github.com/google/sqlcommenter/go/database/sql" sqlcommentercore "github.com/google/sqlcommenter/go/core" _ "github.com/lib/pq" // or any other database driver ) var ( db *sql.DB err error ) db, err = gosql.Open("", "", sqlcommentercore.CommenterOptions{ Config: sqlcommentercore.CommenterConfig{:bool} Tags : sqlcommentercore.StaticTags{: string} // optional }) ``` -------------------------------- ### Forum Service Implementation Source: https://google.github.io/sqlcommenter/java/hibernate Implements the ForumService interface, handling post creation, retrieval, and transaction management. ```java // In file ForumServiceImpl.java package com.google.cloud.sqlcommenter.spring.jpa.service; import com.google.cloud.sqlcommenter.spring.jpa.dao.PostRepository; import com.google.cloud.sqlcommenter.spring.jpa.dao.TagRepository; import com.google.cloud.sqlcommenter.spring.jpa.domain.Post; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Arrays; import java.util.List; @Service public class ForumServiceImpl implements ForumService { @Autowired private PostRepository postRepository; @Autowired private TagRepository tagRepository; @Override @Transactional public Post createPost(String title, String... tags) { Post post = new Post(); post.setTitle(title); post.getTags().addAll(tagRepository.findByNameIn(Arrays.asList(tags))); return postRepository.save(post); } @Override @Transactional(readOnly = true) public List findPostsByTitle(String title) { return postRepository.findByTitle(title); } @Override @Transactional public Post findPostById(Long id) { return postRepository.findById(id).orElse(null); } } ``` -------------------------------- ### SQLCommenter Drop-in Replacement for database/sql (Go) Source: https://google.github.io/sqlcommenter/tags/go SQLCommenter provides a drop-in replacement for Go's database/sql library. You can start using SQLCommenter’s database/sql without changing your business logic code and use one of the framework instrumentation to propagate tags and traceparent to the SQL queries. ```go Please use the sqlcommenter’s go-sql database driver to open a connection and use that connection to execute statements. Due to inherent nature of Go, the safer way to pass information from framework to database driver is via context. ``` -------------------------------- ### Psycopg2 with libpq Version Information Source: https://google.github.io/sqlcommenter/python/psycopg2 Includes libpq version information in SQL comments via SQL Commenter. Requires psycopg2. Ensure DSN is correctly configured. ```python #!/usr/bin/env python3 import psycopg2 from google.cloud.sqlommenter.psycopg2.extension import CommenterCursorFactory DSN = '...' # DB connection info def main(): cursor_factory = CommenterCursorFactory(with_libpq_version=True) with psycopg2.connect(DSN, cursor_factory=cursor_factory) as conn: with conn.cursor() as cursor: cursor.execute("SELECT * FROM polls_question") for row in cursor: print(row) if __name__ == '__main__': main() ``` -------------------------------- ### Configure Gorilla Mux with SQLCommenter Middleware Source: https://google.github.io/sqlcommenter/tags/gorrila Apply the SQLCommenterMiddleware to your Gorilla Mux router. This middleware intercepts incoming requests and adds SQLCommenter tags to the context. ```go import ( "net/http" sqlcommentermux "github.com/google/sqlcommenter/go/gorrila/mux" "github.com/gorilla/mux" ) func runApp() { r := mux.NewRouter() r.Use(sqlcommentermux.SQLCommenterMiddleware) r.HandleFunc("/", ActionHome).Methods("GET") http.ListenAndServe(":8080", r) } ``` -------------------------------- ### SQLAlchemy with OpenCensus Source: https://google.github.io/sqlcommenter/python/sqlalchemy Integrates SQLCommenter with OpenCensus for tracing. Ensure you have OpenCensus configured. ```python #!/usr/bin/env python3 from sqlalchemy import create_engine, event from google.cloud.sqlcommenter.sqlalchemy.executor import BeforeExecuteFactory def main(): tracer = Tracer(exporter=NoopExporter, sampler=AlwaysOnSampler()) engine = create_engine(DB_URL) listener = BeforeExecuteFactory(with_opencensus=True) event.listen(engine, 'before_cursor_execute', listener, retval=True) with tracer.span(): result = engine.execute('SELECT * FROM polls_question') for row in result: print(row) if __name__ == '__main__': main() ``` -------------------------------- ### Wrap Knex with SQLCommenter Middleware Source: https://google.github.io/sqlcommenter/node/knex Configure and wrap the Knex instance with SQLCommenter middleware to automatically add tracing information to your queries. Ensure the necessary options like traceparent, tracestate, and optionally db_driver and route are provided, along with the TraceProvider. ```javascript const wrapMainKnexAsMiddleware = require("@sqlcommenter/knex"); const knex = require('knex')({ client: 'pg', connection: { host : '127.0.0.1', user : 'root', password : '' } }); app.use( wrapMainKnexAsMiddleware( knex, { traceparent: true, tracestate: true, // Optional db_driver: true, route: true, }, { TraceProvider: "OpenTelemetry" } ) ); app.get('/', (req, res) => res.send('Hello, sqlcommenter-nodejs!!')); app.get('^/polls/:param', function(req, res) { knex.raw('SELECT * from polls_question').then(function(polls) { const blob = JSON.stringify(polls); res.send(blob); }).catch(function(err) { console.log(err); res.send(500); }); }); app.listen(port, () => console.log(`Application listening on ${port}`)); ``` -------------------------------- ### Django settings.py with OpenCensus and SQLCommenter Source: https://google.github.io/sqlcommenter/python/django Configure Django settings for both OpenCensus and SQLCommenter, disabling default fields. ```python # settings.py INSTALLED_APPS = [ 'opencensus.ext.django', ... ] MIDDLEWARE = [ 'opencensus.ext.django.middleware.OpencensusMiddleware', 'sqlcommenter.django.middleware.SqlCommenter', ... ] OPENCENSUS = { 'TRACE': { 'SAMPLER': 'opencensus.trace.samplers.AlwaysOnSampler()', } } SQLCOMMENTER_WITH_CONTROLLER = False SQLCOMMENTER_WITH_FRAMEWORK = False SQLCOMMENTER_WITH_ROUTE = False SQLCOMMENTER_WITH_OPENCENSUS = True ```