text,length,is_long_context,metric_val,label_metric "* xref:user-guide/index.adoc[User guide] ** xref:user-guide/index.adoc[Getting started] *** xref:user-guide/getting-started/try-it-out-locally.adoc[Try it locally] *** xref:user-guide/getting-started/try-it-out-on-kubernetes.adoc[Try it on Kubernetes] *** xref:user-guide/getting-started/try-it-out-on-openshift-with-strimzi.adoc[Try it on OpenShift cluster] *** xref:user-guide/getting-started/getting-started-with-packages.adoc[Packages documentation] ** xref:user-guide/basic-concepts.adoc[Basic concepts] ** xref:user-guide/basic-configuration.adoc[Basic configuration] ** xref:user-guide/aggregation.adoc[Aggregation] ** xref:user-guide/idempotency.adoc[Idempotency] ** xref:user-guide/remove-headers.adoc[Remove Headers] ** xref:user-guide/extending-connector/index.adoc[Extending a Connector] *** xref:user-guide/extending-connector/archetype-connector.adoc[Extensible connector archetype] *** xref:user-guide/extending-connector/archetype-dataformat-connector.adoc[Extensible Dataformat connector archetype] *** xref:user-guide/extending-connector/archetype-apicurio-connector.adoc[Extensible Apicurio connector archetype] ** xref:user-guide/camel-compatibility-matrix.adoc[Apache Camel compatibility matrix] * xref:contributor-guide/index.adoc[Contributor guide] ** xref:contributor-guide/testing.adoc[Testing] ** xref:contributor-guide/troubleshooting.adoc[Troubleshooting] ** xref:contributor-guide/release-guide.adoc[Release Guide] * xref:reference/index.adoc[Reference] ** xref:reference/transformers/index.adoc[Single Message Transformers (SMT)] *** xref:reference/transformers/fieldsToHeaders.adoc[Fields To Headers] ** xref:reference/index.adoc[Connectors] // connectors: START *** camel-activemq-kafka-connector **** xref:reference/connectors/camel-activemq-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-activemq-kafka-sink-connector.adoc[Sink Docs] *** camel-ahc-kafka-connector **** xref:reference/connectors/camel-ahc-kafka-sink-connector.adoc[Sink Docs] *** camel-ahc-ws-kafka-connector **** xref:reference/connectors/camel-ahc-ws-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-ahc-ws-kafka-sink-connector.adoc[Sink Docs] *** camel-ahc-wss-kafka-connector **** xref:reference/connectors/camel-ahc-wss-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-ahc-wss-kafka-sink-connector.adoc[Sink Docs] *** camel-amqp-kafka-connector **** xref:reference/connectors/camel-amqp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-amqp-kafka-sink-connector.adoc[Sink Docs] *** camel-arangodb-kafka-connector **** xref:reference/connectors/camel-arangodb-kafka-sink-connector.adoc[Sink Docs] *** camel-as2-kafka-connector **** xref:reference/connectors/camel-as2-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-as2-kafka-sink-connector.adoc[Sink Docs] *** camel-asterisk-kafka-connector **** xref:reference/connectors/camel-asterisk-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-asterisk-kafka-sink-connector.adoc[Sink Docs] *** camel-atlasmap-kafka-connector **** xref:reference/connectors/camel-atlasmap-kafka-sink-connector.adoc[Sink Docs] *** camel-atmos-kafka-connector **** xref:reference/connectors/camel-atmos-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-atmos-kafka-sink-connector.adoc[Sink Docs] *** camel-atmosphere-websocket-kafka-connector **** xref:reference/connectors/camel-atmosphere-websocket-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-atmosphere-websocket-kafka-sink-connector.adoc[Sink Docs] *** camel-atom-kafka-connector **** xref:reference/connectors/camel-atom-kafka-source-connector.adoc[Source Docs] *** camel-atomix-map-kafka-connector **** xref:reference/connectors/camel-atomix-map-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-atomix-map-kafka-sink-connector.adoc[Sink Docs] *** camel-atomix-messaging-kafka-connector **** xref:reference/connectors/camel-atomix-messaging-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-atomix-messaging-kafka-sink-connector.adoc[Sink Docs] *** camel-atomix-multimap-kafka-connector **** xref:reference/connectors/camel-atomix-multimap-kafka-sink-connector.adoc[Sink Docs] *** camel-atomix-queue-kafka-connector **** xref:reference/connectors/camel-atomix-queue-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-atomix-queue-kafka-sink-connector.adoc[Sink Docs] *** camel-atomix-set-kafka-connector **** xref:reference/connectors/camel-atomix-set-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-atomix-set-kafka-sink-connector.adoc[Sink Docs] *** camel-atomix-value-kafka-connector **** xref:reference/connectors/camel-atomix-value-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-atomix-value-kafka-sink-connector.adoc[Sink Docs] *** camel-avro-kafka-connector **** xref:reference/connectors/camel-avro-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-avro-kafka-sink-connector.adoc[Sink Docs] *** camel-aws-secrets-manager-kafka-connector **** xref:reference/connectors/camel-aws-secrets-manager-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-athena-kafka-connector **** xref:reference/connectors/camel-aws2-athena-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-cw-kafka-connector **** xref:reference/connectors/camel-aws2-cw-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-ddb-kafka-connector **** xref:reference/connectors/camel-aws2-ddb-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-ddbstream-kafka-connector **** xref:reference/connectors/camel-aws2-ddbstream-kafka-source-connector.adoc[Source Docs] *** camel-aws2-ec2-kafka-connector **** xref:reference/connectors/camel-aws2-ec2-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-ecs-kafka-connector **** xref:reference/connectors/camel-aws2-ecs-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-eks-kafka-connector **** xref:reference/connectors/camel-aws2-eks-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-eventbridge-kafka-connector **** xref:reference/connectors/camel-aws2-eventbridge-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-iam-kafka-connector **** xref:reference/connectors/camel-aws2-iam-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-kinesis-firehose-kafka-connector **** xref:reference/connectors/camel-aws2-kinesis-firehose-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-kinesis-kafka-connector **** xref:reference/connectors/camel-aws2-kinesis-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-aws2-kinesis-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-kms-kafka-connector **** xref:reference/connectors/camel-aws2-kms-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-lambda-kafka-connector **** xref:reference/connectors/camel-aws2-lambda-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-mq-kafka-connector **** xref:reference/connectors/camel-aws2-mq-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-msk-kafka-connector **** xref:reference/connectors/camel-aws2-msk-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-s3-kafka-connector **** xref:reference/connectors/camel-aws2-s3-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-aws2-s3-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-ses-kafka-connector **** xref:reference/connectors/camel-aws2-ses-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-sns-kafka-connector **** xref:reference/connectors/camel-aws2-sns-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-sqs-kafka-connector **** xref:reference/connectors/camel-aws2-sqs-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-aws2-sqs-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-sts-kafka-connector **** xref:reference/connectors/camel-aws2-sts-kafka-sink-connector.adoc[Sink Docs] *** camel-aws2-translate-kafka-connector **** xref:reference/connectors/camel-aws2-translate-kafka-sink-connector.adoc[Sink Docs] *** camel-azure-cosmosdb-kafka-connector **** xref:reference/connectors/camel-azure-cosmosdb-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-azure-cosmosdb-kafka-sink-connector.adoc[Sink Docs] *** camel-azure-eventhubs-kafka-connector **** xref:reference/connectors/camel-azure-eventhubs-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-azure-eventhubs-kafka-sink-connector.adoc[Sink Docs] *** camel-azure-storage-blob-kafka-connector **** xref:reference/connectors/camel-azure-storage-blob-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-azure-storage-blob-kafka-sink-connector.adoc[Sink Docs] *** camel-azure-storage-datalake-kafka-connector **** xref:reference/connectors/camel-azure-storage-datalake-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-azure-storage-datalake-kafka-sink-connector.adoc[Sink Docs] *** camel-azure-storage-queue-kafka-connector **** xref:reference/connectors/camel-azure-storage-queue-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-azure-storage-queue-kafka-sink-connector.adoc[Sink Docs] *** camel-bean-kafka-connector **** xref:reference/connectors/camel-bean-kafka-sink-connector.adoc[Sink Docs] *** camel-beanstalk-kafka-connector **** xref:reference/connectors/camel-beanstalk-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-beanstalk-kafka-sink-connector.adoc[Sink Docs] *** camel-box-kafka-connector **** xref:reference/connectors/camel-box-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-box-kafka-sink-connector.adoc[Sink Docs] *** camel-braintree-kafka-connector **** xref:reference/connectors/camel-braintree-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-braintree-kafka-sink-connector.adoc[Sink Docs] *** camel-caffeine-cache-kafka-connector **** xref:reference/connectors/camel-caffeine-cache-kafka-sink-connector.adoc[Sink Docs] *** camel-caffeine-loadcache-kafka-connector **** xref:reference/connectors/camel-caffeine-loadcache-kafka-sink-connector.adoc[Sink Docs] *** camel-chatscript-kafka-connector **** xref:reference/connectors/camel-chatscript-kafka-sink-connector.adoc[Sink Docs] *** camel-chunk-kafka-connector **** xref:reference/connectors/camel-chunk-kafka-sink-connector.adoc[Sink Docs] *** camel-cm-sms-kafka-connector **** xref:reference/connectors/camel-cm-sms-kafka-sink-connector.adoc[Sink Docs] *** camel-cmis-kafka-connector **** xref:reference/connectors/camel-cmis-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-cmis-kafka-sink-connector.adoc[Sink Docs] *** camel-coap-kafka-connector **** xref:reference/connectors/camel-coap-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-coap-kafka-sink-connector.adoc[Sink Docs] *** camel-coap-tcp-kafka-connector **** xref:reference/connectors/camel-coap+tcp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-coap+tcp-kafka-sink-connector.adoc[Sink Docs] *** camel-coaps-kafka-connector **** xref:reference/connectors/camel-coaps-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-coaps-kafka-sink-connector.adoc[Sink Docs] *** camel-coaps-tcp-kafka-connector **** xref:reference/connectors/camel-coaps+tcp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-coaps+tcp-kafka-sink-connector.adoc[Sink Docs] *** camel-cometd-kafka-connector **** xref:reference/connectors/camel-cometd-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-cometd-kafka-sink-connector.adoc[Sink Docs] *** camel-cometds-kafka-connector **** xref:reference/connectors/camel-cometds-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-cometds-kafka-sink-connector.adoc[Sink Docs] *** camel-consul-kafka-connector **** xref:reference/connectors/camel-consul-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-consul-kafka-sink-connector.adoc[Sink Docs] *** camel-controlbus-kafka-connector **** xref:reference/connectors/camel-controlbus-kafka-sink-connector.adoc[Sink Docs] *** camel-corda-kafka-connector **** xref:reference/connectors/camel-corda-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-corda-kafka-sink-connector.adoc[Sink Docs] *** camel-couchbase-kafka-connector **** xref:reference/connectors/camel-couchbase-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-couchbase-kafka-sink-connector.adoc[Sink Docs] *** camel-couchdb-kafka-connector **** xref:reference/connectors/camel-couchdb-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-couchdb-kafka-sink-connector.adoc[Sink Docs] *** camel-cql-kafka-connector **** xref:reference/connectors/camel-cql-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-cql-kafka-sink-connector.adoc[Sink Docs] *** camel-cron-kafka-connector **** xref:reference/connectors/camel-cron-kafka-source-connector.adoc[Source Docs] *** camel-crypto-kafka-connector **** xref:reference/connectors/camel-crypto-kafka-sink-connector.adoc[Sink Docs] *** camel-cxf-kafka-connector **** xref:reference/connectors/camel-cxf-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-cxf-kafka-sink-connector.adoc[Sink Docs] *** camel-cxfrs-kafka-connector **** xref:reference/connectors/camel-cxfrs-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-cxfrs-kafka-sink-connector.adoc[Sink Docs] *** camel-dataformat-kafka-connector **** xref:reference/connectors/camel-dataformat-kafka-sink-connector.adoc[Sink Docs] *** camel-direct-kafka-connector **** xref:reference/connectors/camel-direct-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-direct-kafka-sink-connector.adoc[Sink Docs] *** camel-direct-vm-kafka-connector **** xref:reference/connectors/camel-direct-vm-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-direct-vm-kafka-sink-connector.adoc[Sink Docs] *** camel-disruptor-kafka-connector **** xref:reference/connectors/camel-disruptor-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-disruptor-kafka-sink-connector.adoc[Sink Docs] *** camel-disruptor-vm-kafka-connector **** xref:reference/connectors/camel-disruptor-vm-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-disruptor-vm-kafka-sink-connector.adoc[Sink Docs] *** camel-djl-kafka-connector **** xref:reference/connectors/camel-djl-kafka-sink-connector.adoc[Sink Docs] *** camel-dns-kafka-connector **** xref:reference/connectors/camel-dns-kafka-sink-connector.adoc[Sink Docs] *** camel-docker-kafka-connector **** xref:reference/connectors/camel-docker-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-docker-kafka-sink-connector.adoc[Sink Docs] *** camel-dozer-kafka-connector **** xref:reference/connectors/camel-dozer-kafka-sink-connector.adoc[Sink Docs] *** camel-drill-kafka-connector **** xref:reference/connectors/camel-drill-kafka-sink-connector.adoc[Sink Docs] *** camel-dropbox-kafka-connector **** xref:reference/connectors/camel-dropbox-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-dropbox-kafka-sink-connector.adoc[Sink Docs] *** camel-ehcache-kafka-connector **** xref:reference/connectors/camel-ehcache-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-ehcache-kafka-sink-connector.adoc[Sink Docs] *** camel-elasticsearch-rest-kafka-connector **** xref:reference/connectors/camel-elasticsearch-rest-kafka-sink-connector.adoc[Sink Docs] *** camel-elsql-kafka-connector **** xref:reference/connectors/camel-elsql-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-elsql-kafka-sink-connector.adoc[Sink Docs] *** camel-elytron-kafka-connector **** xref:reference/connectors/camel-elytron-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-elytron-kafka-sink-connector.adoc[Sink Docs] *** camel-etcd-keys-kafka-connector **** xref:reference/connectors/camel-etcd-keys-kafka-sink-connector.adoc[Sink Docs] *** camel-etcd-stats-kafka-connector **** xref:reference/connectors/camel-etcd-stats-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-etcd-stats-kafka-sink-connector.adoc[Sink Docs] *** camel-etcd-watch-kafka-connector **** xref:reference/connectors/camel-etcd-watch-kafka-source-connector.adoc[Source Docs] *** camel-exec-kafka-connector **** xref:reference/connectors/camel-exec-kafka-sink-connector.adoc[Sink Docs] *** camel-facebook-kafka-connector **** xref:reference/connectors/camel-facebook-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-facebook-kafka-sink-connector.adoc[Sink Docs] *** camel-fhir-kafka-connector **** xref:reference/connectors/camel-fhir-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-fhir-kafka-sink-connector.adoc[Sink Docs] *** camel-file-kafka-connector **** xref:reference/connectors/camel-file-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-file-kafka-sink-connector.adoc[Sink Docs] *** camel-file-watch-kafka-connector **** xref:reference/connectors/camel-file-watch-kafka-source-connector.adoc[Source Docs] *** camel-flatpack-kafka-connector **** xref:reference/connectors/camel-flatpack-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-flatpack-kafka-sink-connector.adoc[Sink Docs] *** camel-flink-kafka-connector **** xref:reference/connectors/camel-flink-kafka-sink-connector.adoc[Sink Docs] *** camel-fop-kafka-connector **** xref:reference/connectors/camel-fop-kafka-sink-connector.adoc[Sink Docs] *** camel-freemarker-kafka-connector **** xref:reference/connectors/camel-freemarker-kafka-sink-connector.adoc[Sink Docs] *** camel-ftp-kafka-connector **** xref:reference/connectors/camel-ftp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-ftp-kafka-sink-connector.adoc[Sink Docs] *** camel-ftps-kafka-connector **** xref:reference/connectors/camel-ftps-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-ftps-kafka-sink-connector.adoc[Sink Docs] *** camel-ganglia-kafka-connector **** xref:reference/connectors/camel-ganglia-kafka-sink-connector.adoc[Sink Docs] *** camel-geocoder-kafka-connector **** xref:reference/connectors/camel-geocoder-kafka-sink-connector.adoc[Sink Docs] *** camel-git-kafka-connector **** xref:reference/connectors/camel-git-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-git-kafka-sink-connector.adoc[Sink Docs] *** camel-github-kafka-connector **** xref:reference/connectors/camel-github-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-github-kafka-sink-connector.adoc[Sink Docs] *** camel-google-bigquery-kafka-connector **** xref:reference/connectors/camel-google-bigquery-kafka-sink-connector.adoc[Sink Docs] *** camel-google-bigquery-sql-kafka-connector **** xref:reference/connectors/camel-google-bigquery-sql-kafka-sink-connector.adoc[Sink Docs] *** camel-google-calendar-kafka-connector **** xref:reference/connectors/camel-google-calendar-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-google-calendar-kafka-sink-connector.adoc[Sink Docs] *** camel-google-calendar-stream-kafka-connector **** xref:reference/connectors/camel-google-calendar-stream-kafka-source-connector.adoc[Source Docs] *** camel-google-drive-kafka-connector **** xref:reference/connectors/camel-google-drive-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-google-drive-kafka-sink-connector.adoc[Sink Docs] *** camel-google-functions-kafka-connector **** xref:reference/connectors/camel-google-functions-kafka-sink-connector.adoc[Sink Docs] *** camel-google-mail-kafka-connector **** xref:reference/connectors/camel-google-mail-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-google-mail-kafka-sink-connector.adoc[Sink Docs] *** camel-google-mail-stream-kafka-connector **** xref:reference/connectors/camel-google-mail-stream-kafka-source-connector.adoc[Source Docs] *** camel-google-pubsub-kafka-connector **** xref:reference/connectors/camel-google-pubsub-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-google-pubsub-kafka-sink-connector.adoc[Sink Docs] *** camel-google-sheets-kafka-connector **** xref:reference/connectors/camel-google-sheets-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-google-sheets-kafka-sink-connector.adoc[Sink Docs] *** camel-google-sheets-stream-kafka-connector **** xref:reference/connectors/camel-google-sheets-stream-kafka-source-connector.adoc[Source Docs] *** camel-google-storage-kafka-connector **** xref:reference/connectors/camel-google-storage-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-google-storage-kafka-sink-connector.adoc[Sink Docs] *** camel-gora-kafka-connector **** xref:reference/connectors/camel-gora-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-gora-kafka-sink-connector.adoc[Sink Docs] *** camel-grape-kafka-connector **** xref:reference/connectors/camel-grape-kafka-sink-connector.adoc[Sink Docs] *** camel-graphql-kafka-connector **** xref:reference/connectors/camel-graphql-kafka-sink-connector.adoc[Sink Docs] *** camel-grpc-kafka-connector **** xref:reference/connectors/camel-grpc-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-grpc-kafka-sink-connector.adoc[Sink Docs] *** camel-guava-eventbus-kafka-connector **** xref:reference/connectors/camel-guava-eventbus-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-guava-eventbus-kafka-sink-connector.adoc[Sink Docs] *** camel-hazelcast-atomicvalue-kafka-connector **** xref:reference/connectors/camel-hazelcast-atomicvalue-kafka-sink-connector.adoc[Sink Docs] *** camel-hazelcast-instance-kafka-connector **** xref:reference/connectors/camel-hazelcast-instance-kafka-source-connector.adoc[Source Docs] *** camel-hazelcast-list-kafka-connector **** xref:reference/connectors/camel-hazelcast-list-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-hazelcast-list-kafka-sink-connector.adoc[Sink Docs] *** camel-hazelcast-map-kafka-connector **** xref:reference/connectors/camel-hazelcast-map-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-hazelcast-map-kafka-sink-connector.adoc[Sink Docs] *** camel-hazelcast-multimap-kafka-connector **** xref:reference/connectors/camel-hazelcast-multimap-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-hazelcast-multimap-kafka-sink-connector.adoc[Sink Docs] *** camel-hazelcast-queue-kafka-connector **** xref:reference/connectors/camel-hazelcast-queue-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-hazelcast-queue-kafka-sink-connector.adoc[Sink Docs] *** camel-hazelcast-replicatedmap-kafka-connector **** xref:reference/connectors/camel-hazelcast-replicatedmap-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-hazelcast-replicatedmap-kafka-sink-connector.adoc[Sink Docs] *** camel-hazelcast-ringbuffer-kafka-connector **** xref:reference/connectors/camel-hazelcast-ringbuffer-kafka-sink-connector.adoc[Sink Docs] *** camel-hazelcast-seda-kafka-connector **** xref:reference/connectors/camel-hazelcast-seda-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-hazelcast-seda-kafka-sink-connector.adoc[Sink Docs] *** camel-hazelcast-set-kafka-connector **** xref:reference/connectors/camel-hazelcast-set-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-hazelcast-set-kafka-sink-connector.adoc[Sink Docs] *** camel-hazelcast-topic-kafka-connector **** xref:reference/connectors/camel-hazelcast-topic-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-hazelcast-topic-kafka-sink-connector.adoc[Sink Docs] *** camel-hbase-kafka-connector **** xref:reference/connectors/camel-hbase-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-hbase-kafka-sink-connector.adoc[Sink Docs] *** camel-hdfs-kafka-connector **** xref:reference/connectors/camel-hdfs-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-hdfs-kafka-sink-connector.adoc[Sink Docs] *** camel-http-kafka-connector **** xref:reference/connectors/camel-http-kafka-sink-connector.adoc[Sink Docs] *** camel-https-kafka-connector **** xref:reference/connectors/camel-https-kafka-sink-connector.adoc[Sink Docs] *** camel-hwcloud-functiongraph-kafka-connector **** xref:reference/connectors/camel-hwcloud-functiongraph-kafka-sink-connector.adoc[Sink Docs] *** camel-hwcloud-smn-kafka-connector **** xref:reference/connectors/camel-hwcloud-smn-kafka-sink-connector.adoc[Sink Docs] *** camel-iec60870-client-kafka-connector **** xref:reference/connectors/camel-iec60870-client-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-iec60870-client-kafka-sink-connector.adoc[Sink Docs] *** camel-iec60870-server-kafka-connector **** xref:reference/connectors/camel-iec60870-server-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-iec60870-server-kafka-sink-connector.adoc[Sink Docs] *** camel-ignite-cache-kafka-connector **** xref:reference/connectors/camel-ignite-cache-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-ignite-cache-kafka-sink-connector.adoc[Sink Docs] *** camel-ignite-compute-kafka-connector **** xref:reference/connectors/camel-ignite-compute-kafka-sink-connector.adoc[Sink Docs] *** camel-ignite-events-kafka-connector **** xref:reference/connectors/camel-ignite-events-kafka-source-connector.adoc[Source Docs] *** camel-ignite-idgen-kafka-connector **** xref:reference/connectors/camel-ignite-idgen-kafka-sink-connector.adoc[Sink Docs] *** camel-ignite-messaging-kafka-connector **** xref:reference/connectors/camel-ignite-messaging-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-ignite-messaging-kafka-sink-connector.adoc[Sink Docs] *** camel-ignite-queue-kafka-connector **** xref:reference/connectors/camel-ignite-queue-kafka-sink-connector.adoc[Sink Docs] *** camel-ignite-set-kafka-connector **** xref:reference/connectors/camel-ignite-set-kafka-sink-connector.adoc[Sink Docs] *** camel-imap-kafka-connector **** xref:reference/connectors/camel-imap-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-imap-kafka-sink-connector.adoc[Sink Docs] *** camel-imaps-kafka-connector **** xref:reference/connectors/camel-imaps-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-imaps-kafka-sink-connector.adoc[Sink Docs] *** camel-infinispan-embedded-kafka-connector **** xref:reference/connectors/camel-infinispan-embedded-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-infinispan-embedded-kafka-sink-connector.adoc[Sink Docs] *** camel-infinispan-kafka-connector **** xref:reference/connectors/camel-infinispan-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-infinispan-kafka-sink-connector.adoc[Sink Docs] *** camel-influxdb-kafka-connector **** xref:reference/connectors/camel-influxdb-kafka-sink-connector.adoc[Sink Docs] *** camel-iota-kafka-connector **** xref:reference/connectors/camel-iota-kafka-sink-connector.adoc[Sink Docs] *** camel-ipfs-kafka-connector **** xref:reference/connectors/camel-ipfs-kafka-sink-connector.adoc[Sink Docs] *** camel-irc-kafka-connector **** xref:reference/connectors/camel-irc-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-irc-kafka-sink-connector.adoc[Sink Docs] *** camel-ironmq-kafka-connector **** xref:reference/connectors/camel-ironmq-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-ironmq-kafka-sink-connector.adoc[Sink Docs] *** camel-jbpm-kafka-connector **** xref:reference/connectors/camel-jbpm-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jbpm-kafka-sink-connector.adoc[Sink Docs] *** camel-jcache-kafka-connector **** xref:reference/connectors/camel-jcache-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jcache-kafka-sink-connector.adoc[Sink Docs] *** camel-jclouds-kafka-connector **** xref:reference/connectors/camel-jclouds-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jclouds-kafka-sink-connector.adoc[Sink Docs] *** camel-jcr-kafka-connector **** xref:reference/connectors/camel-jcr-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jcr-kafka-sink-connector.adoc[Sink Docs] *** camel-jdbc-kafka-connector **** xref:reference/connectors/camel-jdbc-kafka-sink-connector.adoc[Sink Docs] *** camel-jetty-kafka-connector **** xref:reference/connectors/camel-jetty-kafka-source-connector.adoc[Source Docs] *** camel-jgroups-kafka-connector **** xref:reference/connectors/camel-jgroups-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jgroups-kafka-sink-connector.adoc[Sink Docs] *** camel-jgroups-raft-kafka-connector **** xref:reference/connectors/camel-jgroups-raft-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jgroups-raft-kafka-sink-connector.adoc[Sink Docs] *** camel-jing-kafka-connector **** xref:reference/connectors/camel-jing-kafka-sink-connector.adoc[Sink Docs] *** camel-jira-kafka-connector **** xref:reference/connectors/camel-jira-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jira-kafka-sink-connector.adoc[Sink Docs] *** camel-jms-kafka-connector **** xref:reference/connectors/camel-jms-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jms-kafka-sink-connector.adoc[Sink Docs] *** camel-jmx-kafka-connector **** xref:reference/connectors/camel-jmx-kafka-source-connector.adoc[Source Docs] *** camel-jolt-kafka-connector **** xref:reference/connectors/camel-jolt-kafka-sink-connector.adoc[Sink Docs] *** camel-jooq-kafka-connector **** xref:reference/connectors/camel-jooq-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jooq-kafka-sink-connector.adoc[Sink Docs] *** camel-jpa-kafka-connector **** xref:reference/connectors/camel-jpa-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jpa-kafka-sink-connector.adoc[Sink Docs] *** camel-jslt-kafka-connector **** xref:reference/connectors/camel-jslt-kafka-sink-connector.adoc[Sink Docs] *** camel-json-validator-kafka-connector **** xref:reference/connectors/camel-json-validator-kafka-sink-connector.adoc[Sink Docs] *** camel-jsonata-kafka-connector **** xref:reference/connectors/camel-jsonata-kafka-sink-connector.adoc[Sink Docs] *** camel-jt400-kafka-connector **** xref:reference/connectors/camel-jt400-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-jt400-kafka-sink-connector.adoc[Sink Docs] *** camel-kafka-kafka-connector **** xref:reference/connectors/camel-kafka-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kafka-kafka-sink-connector.adoc[Sink Docs] *** camel-kamelet-kafka-connector **** xref:reference/connectors/camel-kamelet-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kamelet-kafka-sink-connector.adoc[Sink Docs] *** camel-kamelet-reify-kafka-connector **** xref:reference/connectors/camel-kamelet-reify-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kamelet-reify-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-config-maps-kafka-connector **** xref:reference/connectors/camel-kubernetes-config-maps-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-custom-resources-kafka-connector **** xref:reference/connectors/camel-kubernetes-custom-resources-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kubernetes-custom-resources-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-deployments-kafka-connector **** xref:reference/connectors/camel-kubernetes-deployments-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kubernetes-deployments-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-hpa-kafka-connector **** xref:reference/connectors/camel-kubernetes-hpa-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kubernetes-hpa-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-job-kafka-connector **** xref:reference/connectors/camel-kubernetes-job-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kubernetes-job-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-namespaces-kafka-connector **** xref:reference/connectors/camel-kubernetes-namespaces-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kubernetes-namespaces-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-nodes-kafka-connector **** xref:reference/connectors/camel-kubernetes-nodes-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kubernetes-nodes-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-persistent-volumes-claims-kafka-connector **** xref:reference/connectors/camel-kubernetes-persistent-volumes-claims-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-persistent-volumes-kafka-connector **** xref:reference/connectors/camel-kubernetes-persistent-volumes-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-pods-kafka-connector **** xref:reference/connectors/camel-kubernetes-pods-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kubernetes-pods-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-replication-controllers-kafka-connector **** xref:reference/connectors/camel-kubernetes-replication-controllers-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kubernetes-replication-controllers-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-resources-quota-kafka-connector **** xref:reference/connectors/camel-kubernetes-resources-quota-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-secrets-kafka-connector **** xref:reference/connectors/camel-kubernetes-secrets-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-service-accounts-kafka-connector **** xref:reference/connectors/camel-kubernetes-service-accounts-kafka-sink-connector.adoc[Sink Docs] *** camel-kubernetes-services-kafka-connector **** xref:reference/connectors/camel-kubernetes-services-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-kubernetes-services-kafka-sink-connector.adoc[Sink Docs] *** camel-kudu-kafka-connector **** xref:reference/connectors/camel-kudu-kafka-sink-connector.adoc[Sink Docs] *** camel-language-kafka-connector **** xref:reference/connectors/camel-language-kafka-sink-connector.adoc[Sink Docs] *** camel-ldap-kafka-connector **** xref:reference/connectors/camel-ldap-kafka-sink-connector.adoc[Sink Docs] *** camel-ldif-kafka-connector **** xref:reference/connectors/camel-ldif-kafka-sink-connector.adoc[Sink Docs] *** camel-log-kafka-connector **** xref:reference/connectors/camel-log-kafka-sink-connector.adoc[Sink Docs] *** camel-lpr-kafka-connector **** xref:reference/connectors/camel-lpr-kafka-sink-connector.adoc[Sink Docs] *** camel-lucene-kafka-connector **** xref:reference/connectors/camel-lucene-kafka-sink-connector.adoc[Sink Docs] *** camel-lumberjack-kafka-connector **** xref:reference/connectors/camel-lumberjack-kafka-source-connector.adoc[Source Docs] *** camel-master-kafka-connector **** xref:reference/connectors/camel-master-kafka-source-connector.adoc[Source Docs] *** camel-metrics-kafka-connector **** xref:reference/connectors/camel-metrics-kafka-sink-connector.adoc[Sink Docs] *** camel-micrometer-kafka-connector **** xref:reference/connectors/camel-micrometer-kafka-sink-connector.adoc[Sink Docs] *** camel-microprofile-metrics-kafka-connector **** xref:reference/connectors/camel-microprofile-metrics-kafka-sink-connector.adoc[Sink Docs] *** camel-milo-client-kafka-connector **** xref:reference/connectors/camel-milo-client-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-milo-client-kafka-sink-connector.adoc[Sink Docs] *** camel-milo-server-kafka-connector **** xref:reference/connectors/camel-milo-server-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-milo-server-kafka-sink-connector.adoc[Sink Docs] *** camel-mina-kafka-connector **** xref:reference/connectors/camel-mina-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-mina-kafka-sink-connector.adoc[Sink Docs] *** camel-minio-kafka-connector **** xref:reference/connectors/camel-minio-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-minio-kafka-sink-connector.adoc[Sink Docs] *** camel-mllp-kafka-connector **** xref:reference/connectors/camel-mllp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-mllp-kafka-sink-connector.adoc[Sink Docs] *** camel-mongodb-gridfs-kafka-connector **** xref:reference/connectors/camel-mongodb-gridfs-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-mongodb-gridfs-kafka-sink-connector.adoc[Sink Docs] *** camel-mongodb-kafka-connector **** xref:reference/connectors/camel-mongodb-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-mongodb-kafka-sink-connector.adoc[Sink Docs] *** camel-msv-kafka-connector **** xref:reference/connectors/camel-msv-kafka-sink-connector.adoc[Sink Docs] *** camel-mustache-kafka-connector **** xref:reference/connectors/camel-mustache-kafka-sink-connector.adoc[Sink Docs] *** camel-mvel-kafka-connector **** xref:reference/connectors/camel-mvel-kafka-sink-connector.adoc[Sink Docs] *** camel-mybatis-bean-kafka-connector **** xref:reference/connectors/camel-mybatis-bean-kafka-sink-connector.adoc[Sink Docs] *** camel-mybatis-kafka-connector **** xref:reference/connectors/camel-mybatis-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-mybatis-kafka-sink-connector.adoc[Sink Docs] *** camel-nagios-kafka-connector **** xref:reference/connectors/camel-nagios-kafka-sink-connector.adoc[Sink Docs] *** camel-nats-kafka-connector **** xref:reference/connectors/camel-nats-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-nats-kafka-sink-connector.adoc[Sink Docs] *** camel-netty-http-kafka-connector **** xref:reference/connectors/camel-netty-http-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-netty-http-kafka-sink-connector.adoc[Sink Docs] *** camel-netty-kafka-connector **** xref:reference/connectors/camel-netty-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-netty-kafka-sink-connector.adoc[Sink Docs] *** camel-nitrite-kafka-connector **** xref:reference/connectors/camel-nitrite-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-nitrite-kafka-sink-connector.adoc[Sink Docs] *** camel-nsq-kafka-connector **** xref:reference/connectors/camel-nsq-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-nsq-kafka-sink-connector.adoc[Sink Docs] *** camel-oaipmh-kafka-connector **** xref:reference/connectors/camel-oaipmh-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-oaipmh-kafka-sink-connector.adoc[Sink Docs] *** camel-olingo2-kafka-connector **** xref:reference/connectors/camel-olingo2-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-olingo2-kafka-sink-connector.adoc[Sink Docs] *** camel-olingo4-kafka-connector **** xref:reference/connectors/camel-olingo4-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-olingo4-kafka-sink-connector.adoc[Sink Docs] *** camel-openshift-build-configs-kafka-connector **** xref:reference/connectors/camel-openshift-build-configs-kafka-sink-connector.adoc[Sink Docs] *** camel-openshift-builds-kafka-connector **** xref:reference/connectors/camel-openshift-builds-kafka-sink-connector.adoc[Sink Docs] *** camel-openstack-cinder-kafka-connector **** xref:reference/connectors/camel-openstack-cinder-kafka-sink-connector.adoc[Sink Docs] *** camel-openstack-glance-kafka-connector **** xref:reference/connectors/camel-openstack-glance-kafka-sink-connector.adoc[Sink Docs] *** camel-openstack-keystone-kafka-connector **** xref:reference/connectors/camel-openstack-keystone-kafka-sink-connector.adoc[Sink Docs] *** camel-openstack-neutron-kafka-connector **** xref:reference/connectors/camel-openstack-neutron-kafka-sink-connector.adoc[Sink Docs] *** camel-openstack-nova-kafka-connector **** xref:reference/connectors/camel-openstack-nova-kafka-sink-connector.adoc[Sink Docs] *** camel-openstack-swift-kafka-connector **** xref:reference/connectors/camel-openstack-swift-kafka-sink-connector.adoc[Sink Docs] *** camel-optaplanner-kafka-connector **** xref:reference/connectors/camel-optaplanner-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-optaplanner-kafka-sink-connector.adoc[Sink Docs] *** camel-paho-kafka-connector **** xref:reference/connectors/camel-paho-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-paho-kafka-sink-connector.adoc[Sink Docs] *** camel-paho-mqtt5-kafka-connector **** xref:reference/connectors/camel-paho-mqtt5-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-paho-mqtt5-kafka-sink-connector.adoc[Sink Docs] *** camel-pdf-kafka-connector **** xref:reference/connectors/camel-pdf-kafka-sink-connector.adoc[Sink Docs] *** camel-pg-replication-slot-kafka-connector **** xref:reference/connectors/camel-pg-replication-slot-kafka-source-connector.adoc[Source Docs] *** camel-pgevent-kafka-connector **** xref:reference/connectors/camel-pgevent-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-pgevent-kafka-sink-connector.adoc[Sink Docs] *** camel-platform-http-kafka-connector **** xref:reference/connectors/camel-platform-http-kafka-source-connector.adoc[Source Docs] *** camel-pop3-kafka-connector **** xref:reference/connectors/camel-pop3-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-pop3-kafka-sink-connector.adoc[Sink Docs] *** camel-pop3s-kafka-connector **** xref:reference/connectors/camel-pop3s-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-pop3s-kafka-sink-connector.adoc[Sink Docs] *** camel-pubnub-kafka-connector **** xref:reference/connectors/camel-pubnub-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-pubnub-kafka-sink-connector.adoc[Sink Docs] *** camel-pulsar-kafka-connector **** xref:reference/connectors/camel-pulsar-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-pulsar-kafka-sink-connector.adoc[Sink Docs] *** camel-quartz-kafka-connector **** xref:reference/connectors/camel-quartz-kafka-source-connector.adoc[Source Docs] *** camel-quickfix-kafka-connector **** xref:reference/connectors/camel-quickfix-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-quickfix-kafka-sink-connector.adoc[Sink Docs] *** camel-rabbitmq-kafka-connector **** xref:reference/connectors/camel-rabbitmq-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-rabbitmq-kafka-sink-connector.adoc[Sink Docs] *** camel-reactive-streams-kafka-connector **** xref:reference/connectors/camel-reactive-streams-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-reactive-streams-kafka-sink-connector.adoc[Sink Docs] *** camel-rest-api-kafka-connector **** xref:reference/connectors/camel-rest-api-kafka-source-connector.adoc[Source Docs] *** camel-rest-kafka-connector **** xref:reference/connectors/camel-rest-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-rest-kafka-sink-connector.adoc[Sink Docs] *** camel-rest-openapi-kafka-connector **** xref:reference/connectors/camel-rest-openapi-kafka-sink-connector.adoc[Sink Docs] *** camel-rest-swagger-kafka-connector **** xref:reference/connectors/camel-rest-swagger-kafka-sink-connector.adoc[Sink Docs] *** camel-resteasy-kafka-connector **** xref:reference/connectors/camel-resteasy-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-resteasy-kafka-sink-connector.adoc[Sink Docs] *** camel-rss-kafka-connector **** xref:reference/connectors/camel-rss-kafka-source-connector.adoc[Source Docs] *** camel-saga-kafka-connector **** xref:reference/connectors/camel-saga-kafka-sink-connector.adoc[Sink Docs] *** camel-salesforce-kafka-connector **** xref:reference/connectors/camel-salesforce-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-salesforce-kafka-sink-connector.adoc[Sink Docs] *** camel-sap-netweaver-kafka-connector **** xref:reference/connectors/camel-sap-netweaver-kafka-sink-connector.adoc[Sink Docs] *** camel-scheduler-kafka-connector **** xref:reference/connectors/camel-scheduler-kafka-source-connector.adoc[Source Docs] *** camel-schematron-kafka-connector **** xref:reference/connectors/camel-schematron-kafka-sink-connector.adoc[Sink Docs] *** camel-scp-kafka-connector **** xref:reference/connectors/camel-scp-kafka-sink-connector.adoc[Sink Docs] *** camel-seda-kafka-connector **** xref:reference/connectors/camel-seda-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-seda-kafka-sink-connector.adoc[Sink Docs] *** camel-service-kafka-connector **** xref:reference/connectors/camel-service-kafka-source-connector.adoc[Source Docs] *** camel-servicenow-kafka-connector **** xref:reference/connectors/camel-servicenow-kafka-sink-connector.adoc[Sink Docs] *** camel-servlet-kafka-connector **** xref:reference/connectors/camel-servlet-kafka-source-connector.adoc[Source Docs] *** camel-sftp-kafka-connector **** xref:reference/connectors/camel-sftp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-sftp-kafka-sink-connector.adoc[Sink Docs] *** camel-sip-kafka-connector **** xref:reference/connectors/camel-sip-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-sip-kafka-sink-connector.adoc[Sink Docs] *** camel-sips-kafka-connector **** xref:reference/connectors/camel-sips-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-sips-kafka-sink-connector.adoc[Sink Docs] *** camel-sjms-batch-kafka-connector **** xref:reference/connectors/camel-sjms-batch-kafka-source-connector.adoc[Source Docs] *** camel-sjms-kafka-connector **** xref:reference/connectors/camel-sjms-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-sjms-kafka-sink-connector.adoc[Sink Docs] *** camel-sjms2-kafka-connector **** xref:reference/connectors/camel-sjms2-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-sjms2-kafka-sink-connector.adoc[Sink Docs] *** camel-slack-kafka-connector **** xref:reference/connectors/camel-slack-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-slack-kafka-sink-connector.adoc[Sink Docs] *** camel-smpp-kafka-connector **** xref:reference/connectors/camel-smpp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-smpp-kafka-sink-connector.adoc[Sink Docs] *** camel-smpps-kafka-connector **** xref:reference/connectors/camel-smpps-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-smpps-kafka-sink-connector.adoc[Sink Docs] *** camel-smtp-kafka-connector **** xref:reference/connectors/camel-smtp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-smtp-kafka-sink-connector.adoc[Sink Docs] *** camel-smtps-kafka-connector **** xref:reference/connectors/camel-smtps-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-smtps-kafka-sink-connector.adoc[Sink Docs] *** camel-snmp-kafka-connector **** xref:reference/connectors/camel-snmp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-snmp-kafka-sink-connector.adoc[Sink Docs] *** camel-solr-kafka-connector **** xref:reference/connectors/camel-solr-kafka-sink-connector.adoc[Sink Docs] *** camel-solrcloud-kafka-connector **** xref:reference/connectors/camel-solrCloud-kafka-sink-connector.adoc[Sink Docs] *** camel-solrs-kafka-connector **** xref:reference/connectors/camel-solrs-kafka-sink-connector.adoc[Sink Docs] *** camel-soroush-kafka-connector **** xref:reference/connectors/camel-soroush-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-soroush-kafka-sink-connector.adoc[Sink Docs] *** camel-spark-kafka-connector **** xref:reference/connectors/camel-spark-kafka-sink-connector.adoc[Sink Docs] *** camel-splunk-hec-kafka-connector **** xref:reference/connectors/camel-splunk-hec-kafka-sink-connector.adoc[Sink Docs] *** camel-splunk-kafka-connector **** xref:reference/connectors/camel-splunk-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-splunk-kafka-sink-connector.adoc[Sink Docs] *** camel-spring-batch-kafka-connector **** xref:reference/connectors/camel-spring-batch-kafka-sink-connector.adoc[Sink Docs] *** camel-spring-event-kafka-connector **** xref:reference/connectors/camel-spring-event-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-spring-event-kafka-sink-connector.adoc[Sink Docs] *** camel-spring-integration-kafka-connector **** xref:reference/connectors/camel-spring-integration-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-spring-integration-kafka-sink-connector.adoc[Sink Docs] *** camel-spring-jdbc-kafka-connector **** xref:reference/connectors/camel-spring-jdbc-kafka-sink-connector.adoc[Sink Docs] *** camel-spring-ldap-kafka-connector **** xref:reference/connectors/camel-spring-ldap-kafka-sink-connector.adoc[Sink Docs] *** camel-spring-rabbitmq-kafka-connector **** xref:reference/connectors/camel-spring-rabbitmq-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-spring-rabbitmq-kafka-sink-connector.adoc[Sink Docs] *** camel-spring-redis-kafka-connector **** xref:reference/connectors/camel-spring-redis-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-spring-redis-kafka-sink-connector.adoc[Sink Docs] *** camel-spring-ws-kafka-connector **** xref:reference/connectors/camel-spring-ws-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-spring-ws-kafka-sink-connector.adoc[Sink Docs] *** camel-sql-kafka-connector **** xref:reference/connectors/camel-sql-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-sql-kafka-sink-connector.adoc[Sink Docs] *** camel-sql-stored-kafka-connector **** xref:reference/connectors/camel-sql-stored-kafka-sink-connector.adoc[Sink Docs] *** camel-ssh-kafka-connector **** xref:reference/connectors/camel-ssh-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-ssh-kafka-sink-connector.adoc[Sink Docs] *** camel-stax-kafka-connector **** xref:reference/connectors/camel-stax-kafka-sink-connector.adoc[Sink Docs] *** camel-stitch-kafka-connector **** xref:reference/connectors/camel-stitch-kafka-sink-connector.adoc[Sink Docs] *** camel-stomp-kafka-connector **** xref:reference/connectors/camel-stomp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-stomp-kafka-sink-connector.adoc[Sink Docs] *** camel-stream-kafka-connector **** xref:reference/connectors/camel-stream-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-stream-kafka-sink-connector.adoc[Sink Docs] *** camel-string-template-kafka-connector **** xref:reference/connectors/camel-string-template-kafka-sink-connector.adoc[Sink Docs] *** camel-stub-kafka-connector **** xref:reference/connectors/camel-stub-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-stub-kafka-sink-connector.adoc[Sink Docs] *** camel-syslog-kafka-connector **** xref:reference/connectors/camel-syslog-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-syslog-kafka-sink-connector.adoc[Sink Docs] *** camel-telegram-kafka-connector **** xref:reference/connectors/camel-telegram-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-telegram-kafka-sink-connector.adoc[Sink Docs] *** camel-thrift-kafka-connector **** xref:reference/connectors/camel-thrift-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-thrift-kafka-sink-connector.adoc[Sink Docs] *** camel-tika-kafka-connector **** xref:reference/connectors/camel-tika-kafka-sink-connector.adoc[Sink Docs] *** camel-timer-kafka-connector **** xref:reference/connectors/camel-timer-kafka-source-connector.adoc[Source Docs] *** camel-twilio-kafka-connector **** xref:reference/connectors/camel-twilio-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-twilio-kafka-sink-connector.adoc[Sink Docs] *** camel-twitter-directmessage-kafka-connector **** xref:reference/connectors/camel-twitter-directmessage-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-twitter-directmessage-kafka-sink-connector.adoc[Sink Docs] *** camel-twitter-search-kafka-connector **** xref:reference/connectors/camel-twitter-search-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-twitter-search-kafka-sink-connector.adoc[Sink Docs] *** camel-twitter-timeline-kafka-connector **** xref:reference/connectors/camel-twitter-timeline-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-twitter-timeline-kafka-sink-connector.adoc[Sink Docs] *** camel-undertow-kafka-connector **** xref:reference/connectors/camel-undertow-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-undertow-kafka-sink-connector.adoc[Sink Docs] *** camel-validator-kafka-connector **** xref:reference/connectors/camel-validator-kafka-sink-connector.adoc[Sink Docs] *** camel-velocity-kafka-connector **** xref:reference/connectors/camel-velocity-kafka-sink-connector.adoc[Sink Docs] *** camel-vertx-http-kafka-connector **** xref:reference/connectors/camel-vertx-http-kafka-sink-connector.adoc[Sink Docs] *** camel-vertx-kafka-connector **** xref:reference/connectors/camel-vertx-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-vertx-kafka-sink-connector.adoc[Sink Docs] *** camel-vertx-kafka-kafka-connector **** xref:reference/connectors/camel-vertx-kafka-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-vertx-kafka-kafka-sink-connector.adoc[Sink Docs] *** camel-vertx-websocket-kafka-connector **** xref:reference/connectors/camel-vertx-websocket-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-vertx-websocket-kafka-sink-connector.adoc[Sink Docs] *** camel-vm-kafka-connector **** xref:reference/connectors/camel-vm-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-vm-kafka-sink-connector.adoc[Sink Docs] *** camel-weather-kafka-connector **** xref:reference/connectors/camel-weather-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-weather-kafka-sink-connector.adoc[Sink Docs] *** camel-web3j-kafka-connector **** xref:reference/connectors/camel-web3j-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-web3j-kafka-sink-connector.adoc[Sink Docs] *** camel-webhook-kafka-connector **** xref:reference/connectors/camel-webhook-kafka-source-connector.adoc[Source Docs] *** camel-websocket-jsr356-kafka-connector **** xref:reference/connectors/camel-websocket-jsr356-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-websocket-jsr356-kafka-sink-connector.adoc[Sink Docs] *** camel-websocket-kafka-connector **** xref:reference/connectors/camel-websocket-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-websocket-kafka-sink-connector.adoc[Sink Docs] *** camel-weka-kafka-connector **** xref:reference/connectors/camel-weka-kafka-sink-connector.adoc[Sink Docs] *** camel-wordpress-kafka-connector **** xref:reference/connectors/camel-wordpress-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-wordpress-kafka-sink-connector.adoc[Sink Docs] *** camel-workday-kafka-connector **** xref:reference/connectors/camel-workday-kafka-sink-connector.adoc[Sink Docs] *** camel-xchange-kafka-connector **** xref:reference/connectors/camel-xchange-kafka-sink-connector.adoc[Sink Docs] *** camel-xj-kafka-connector **** xref:reference/connectors/camel-xj-kafka-sink-connector.adoc[Sink Docs] *** camel-xmlsecurity-sign-kafka-connector **** xref:reference/connectors/camel-xmlsecurity-sign-kafka-sink-connector.adoc[Sink Docs] *** camel-xmlsecurity-verify-kafka-connector **** xref:reference/connectors/camel-xmlsecurity-verify-kafka-sink-connector.adoc[Sink Docs] *** camel-xmpp-kafka-connector **** xref:reference/connectors/camel-xmpp-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-xmpp-kafka-sink-connector.adoc[Sink Docs] *** camel-xquery-kafka-connector **** xref:reference/connectors/camel-xquery-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-xquery-kafka-sink-connector.adoc[Sink Docs] *** camel-xslt-kafka-connector **** xref:reference/connectors/camel-xslt-kafka-sink-connector.adoc[Sink Docs] *** camel-xslt-saxon-kafka-connector **** xref:reference/connectors/camel-xslt-saxon-kafka-sink-connector.adoc[Sink Docs] *** camel-yammer-kafka-connector **** xref:reference/connectors/camel-yammer-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-yammer-kafka-sink-connector.adoc[Sink Docs] *** camel-zendesk-kafka-connector **** xref:reference/connectors/camel-zendesk-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-zendesk-kafka-sink-connector.adoc[Sink Docs] *** camel-zookeeper-kafka-connector **** xref:reference/connectors/camel-zookeeper-kafka-source-connector.adoc[Source Docs] **** xref:reference/connectors/camel-zookeeper-kafka-sink-connector.adoc[Sink Docs] *** camel-zookeeper-master-kafka-connector **** xref:reference/connectors/camel-zookeeper-master-kafka-source-connector.adoc[Source Docs] // connectors: END ",16352,True,5675.112077779847,median "/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the ""License""); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* T-SQL (Transact-SQL, MSSQL) grammar. The MIT License (MIT). Copyright (c) 2015-2016, Ivan Kochurkin (kvanttt@gmail.com), Positive Technologies. Copyright (c) 2016, Scott Ure (scott@redstormsoftware.com). Copyright (c) 2016, Rui Zhang (ruizhang.ccs@gmail.com). Copyright (c) 2016, Marcus Henriksson (kuseman80@gmail.com). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ grammar VerdictSQL; // VERDICT verdict_statement : select_statement | create_sample_statement | delete_sample_statement | show_samples_statement | config_statement | other_statement | create_table | create_table_as_select | create_view | drop_table | drop_view ; //WITH SIZE size=(FLOAT | DECIMAL) '%' (STORE poission_cols=DECIMAL POISSON COLUMNS)? (STRATIFIED BY column_name (',' column_name)*)? create_sample_statement : CREATE (size=(FLOAT | DECIMAL) '%')? (sample_type)? SAMPLE (FROM | OF) original_table=table_name (on_columns)? ; sample_type : UNIFORM | UNIVERSE | STRATIFIED | RECOMMENDED ; on_columns : ON column_name (',' column_name)* ; delete_sample_statement : (DELETE | DROP) (size=(FLOAT | DECIMAL) '%')? (sample_type)? SAMPLES OF original_table=table_name (on_columns)? ; show_samples_statement : SHOW type=(STRATIFIED | UNIFORM | ALL)? SAMPLES ((FOR | OF) database=id)? ; config_statement : config_set_statement | config_get_statement ; other_statement : use_statement | show_tables_statement | show_databases_statement | describe_table_statement | refresh_statement | show_config_statement | create_database | drop_database ; create_database : CREATE ( DATABASE | SCHEMA ) (database=id) ; drop_database : DROP ( DATABASE | SCHEMA ) ( IF EXISTS )? (database=id) ; //config_set_statement: SET key=config_key '=' value=config_value percent='%'?; config_set_statement: SET key=config_key '=' value=config_value; config_get_statement: GET key=config_key; config_key: ID('.' (ID | TRIALS))*; //config_value // : ALL // | UNIFORM // | STRATIFIED // | ON // | OFF // | ID (',' ID)* // | STRING // | DOUBLE_QUOTE_STRING // | DECIMAL // | FLOAT // ; config_value : DOUBLE_QUOTE_ID | STRING | ID (',' ID)* ; SIZE: S I Z E; STORE: S T O R E; POISSON: P O I S S O N; COLUMNS: C O L U M N S; STRATIFIED: S T R A T I F I E D; SHOW: S H O W; UNIFORM: U N I F O R M; SAMPLES: S A M P L E S; GET: G E T; CONFIDENCE: C O N F I D E N C E; TRIALS: T R I A L S; //DOUBLE_QUOTE_STRING: '""' (~'""' | '\\\\""')* '""'; confidence_clause: CONFIDENCE confidence=(FLOAT | DECIMAL) percent='%'?; trials_clause: TRIALS trials=number; table_name_with_sample: table_name SAMPLE size=(FLOAT | DECIMAL) percent='%'? ; // VERDICT tsql_file : sql_clause* EOF ; sql_clause : ddl_clause | other_statement ; // Data Definition Language: https://msdn.microsoft.com/en-us/library/ff848799.aspx) ddl_clause : create_table | create_view | alter_table | alter_database | drop_table | drop_view ; // DML // https://msdn.microsoft.com/en-us/library/ms189499.aspx select_statement : with_expression? EXACT? query_expression order_by_clause? limit_clause? confidence_clause? ';'? ; // https://msdn.microsoft.com/en-us/library/ms177564.aspx output_clause : OUTPUT output_dml_list_elem (',' output_dml_list_elem)* (INTO (LOCAL_ID | table_name) ('(' column_name_list ')')? )? ; output_dml_list_elem : (output_column_name | expression) (AS? column_alias)? // TODO: scalar_expression ; output_column_name : (DELETED | INSERTED | table_name) '.' ('*' | column_name) | DOLLAR_ACTION ; // DDL // https://msdn.microsoft.com/en-us/library/ms174979.aspx create_table : CREATE TABLE table_name '(' column_def_table_constraint (','? column_def_table_constraint)* ','? ')' ; create_table_as_select : CREATE TABLE (IF NOT EXISTS)? table_name STORED_AS_PARQUET? AS select_statement ';'? ; // https://msdn.microsoft.com/en-us/library/ms187956.aspx create_view : CREATE VIEW view_name ('(' column_name (',' column_name)* ')')? AS select_statement (WITH CHECK OPTION)? ';'? ; // https://msdn.microsoft.com/en-us/library/ms190273.aspx alter_table : ALTER TABLE table_name SET '(' LOCK_ESCALATION '=' (AUTO | TABLE | DISABLE) ')' ';'? | ALTER TABLE table_name ADD column_def_table_constraint ';'? ; // https://msdn.microsoft.com/en-us/library/ms174269.aspx alter_database : ALTER DATABASE (database=id | CURRENT) MODIFY NAME '=' new_name=id ';'? ; // https://msdn.microsoft.com/en-us/library/ms173790.aspx drop_table : DROP TABLE (IF EXISTS)? table_name ';'? ; // https://msdn.microsoft.com/en-us/library/ms173492.aspx drop_view : DROP VIEW (IF EXISTS)? view_name (',' view_name)* ';'? ; // Other statements. // https://msdn.microsoft.com/en-us/library/ms189484.aspx set_statment : SET LOCAL_ID ('.' member_name=id)? '=' expression ';'? | SET LOCAL_ID assignment_operator expression ';'? // https://msdn.microsoft.com/en-us/library/ms189837.aspx | set_special ; // https://msdn.microsoft.com/en-us/library/ms188366.aspx use_statement : USE database=id ';'? ; show_tables_statement : SHOW TABLES (IN schema=id)? ';'? ; show_databases_statement : SHOW ( DATABASES | SCHEMAS ) ; describe_table_statement : DESCRIBE table=table_name ';'? ; refresh_statement : REFRESH (schema=id)? ';'? ; show_config_statement : SHOW CONFIG ';'? ; table_type_definition : TABLE '(' column_def_table_constraint (','? column_def_table_constraint)* ')' ; column_def_table_constraint : column_definition | table_constraint ; // https://msdn.microsoft.com/en-us/library/ms187742.aspx column_definition : column_name (data_type | AS expression) null_notnull? ; // https://msdn.microsoft.com/en-us/library/ms186712.aspx column_constraint :(CONSTRAINT id)? null_notnull? ; // https://msdn.microsoft.com/en-us/library/ms188066.aspx table_constraint : (CONSTRAINT id)? '(' column_name_list ')' ; // https://msdn.microsoft.com/en-us/library/ms190356.aspx // Runtime check. set_special : SET id (id | constant | LOCAL_ID | on_off) ';'? // https://msdn.microsoft.com/en-us/library/ms173763.aspx | SET TRANSACTION ISOLATION LEVEL (READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SNAPSHOT | SERIALIZABLE) ';'? // https://msdn.microsoft.com/en-us/library/ms188059.aspx | SET IDENTITY_INSERT table_name on_off ';'? ; // Expression. // https://msdn.microsoft.com/en-us/library/ms190286.aspx // Operator precendence: https://msdn.microsoft.com/en-us/library/ms190276.aspx expression : NULL #primitive_expression | LOCAL_ID #primitive_expression | constant #primitive_expression | true_orfalse #primitive_expression | function_call #function_call_expression | expression COLLATE id #function_call_expression | case_expr #case_expression | full_column_name #column_ref_expression | '(' expression ')' #bracket_expression | '(' subquery ')' #subquery_expression | '~' expression #unary_operator_expression | expression op=('*' | '/' | '%') expression #binary_operator_expression | op=('+' | '-') expression #unary_operator_expression | expression op=('+' | '-' | '&' | '^' | '|' | '||') expression #binary_operator_expression | expression comparison_operator expression #binary_operator_expression | interval #interval_expression ; interval : INTERVAL constant_expression (DAY | DAYS | MONTH | MONTHS | YEAR | YEARS) ; constant_expression : NULL | constant // system functions: https://msdn.microsoft.com/en-us/library/ms187786.aspx | function_call | LOCAL_ID // TODO: remove. | '(' constant_expression ')' ; subquery : select_statement ; dml_table_source : query_specification ; // https://msdn.microsoft.com/en-us/library/ms175972.aspx with_expression : WITH (XMLNAMESPACES ',')? common_table_expression (',' common_table_expression)* ; common_table_expression : expression_name=id ('(' column_name_list ')')? AS '(' select_statement ')' ; update_elem : (full_column_name | LOCAL_ID) ('=' | assignment_operator) expression | udt_column_name=id '.' method_name=id '(' expression_list ')' //| full_column_name '.' WRITE (expression, ) ; // https://msdn.microsoft.com/en-us/library/ms173545.aspx search_condition_list : search_condition (',' search_condition)* ; search_condition : search_condition_or (AND search_condition_or)* ; search_condition_or : search_condition_not (OR search_condition_not)* ; search_condition_not : NOT? predicate ; predicate : EXISTS '(' subquery ')' # exists_predicate | expression comparison_operator expression # comp_expr_predicate | expression comparison_operator (ALL | SOME | ANY) '(' subquery ')' # setcomp_expr_predicate | expression NOT? BETWEEN expression AND expression # comp_between_expr | expression NOT? IN '(' (subquery | expression_list) ')' # in_predicate | expression NOT? LIKE expression (ESCAPE expression)? # like_predicate | expression IS null_notnull # is_predicate | '(' search_condition ')' # bracket_predicate ; query_expression : (query_specification | '(' query_expression ')') union* ; union : (UNION ALL? | EXCEPT | INTERSECT) (query_specification | ('(' query_expression ')')+) ; // https://msdn.microsoft.com/en-us/library/ms176104.aspx query_specification : SELECT (ALL | DISTINCT)? (TOP expression PERCENT? (WITH TIES)?)? select_list // https://msdn.microsoft.com/en-us/library/ms188029.aspx (INTO into_table=table_name)? (FROM (table_source (',' table_source)*))? (WHERE where=search_condition)? // https://msdn.microsoft.com/en-us/library/ms177673.aspx ((GROUP BY group_by_item (',' group_by_item)* (WITH ROLLUP)?) | (GROUP BY ROLLUP '(' group_by_item (',' group_by_item)* ')'))? (HAVING having=search_condition)? ; limit_clause : LIMIT number ; // https://msdn.microsoft.com/en-us/library/ms188385.aspx order_by_clause : ORDER BY order_by_expression (',' order_by_expression)* (OFFSET expression (ROW | ROWS) (FETCH (FIRST | NEXT) expression (ROW | ROWS) ONLY)?)? ; // https://msdn.microsoft.com/en-us/library/ms173812.aspx for_clause : FOR BROWSE | FOR XML AUTO xml_common_directives? | FOR XML PATH ('(' STRING ')')? xml_common_directives? ; xml_common_directives : ',' (BINARY BASE64 | TYPE | ROOT) ; order_by_expression : expression (ASC | DESC)? ; group_by_item : expression /*| rollup_spec | cube_spec | grouping_sets_spec | grand_total*/ ; option_clause // https://msdn.microsoft.com/en-us/library/ms181714.aspx : OPTION '(' option (',' option)* ')' ; option : FAST number_rows=DECIMAL | (HASH | ORDER) GROUP | (MERGE | HASH | CONCAT) UNION | KEEPFIXED PLAN | OPTIMIZE FOR '(' optimize_for_arg (',' optimize_for_arg)* ')' | OPTIMIZE FOR UNKNOWN ; optimize_for_arg : LOCAL_ID (UNKNOWN | '=' constant) ; // https://msdn.microsoft.com/en-us/library/ms176104.aspx select_list : select_list_elem (',' select_list_elem)* ; select_list_elem : (table_name '.')? (STAR | '$' (IDENTITY | ROWGUID)) | column_alias '=' expression | expression (AS? column_alias)? ; partition_by_clause : PARTITION BY expression_list ; // https://msdn.microsoft.com/en-us/library/ms177634.aspx table_source : table_source_item_joined | '(' table_source_item_joined ')' ; table_source_item_joined : table_source_item join_part* ; table_source_item : table_name_with_sample as_table_alias? # sample_table_name_item | table_name_with_hint as_table_alias? # hinted_table_name_item | derived_table (as_table_alias column_alias_list?)? # derived_table_source_item ; change_table : CHANGETABLE '(' CHANGES table_name ',' (NULL | DECIMAL | LOCAL_ID) ')' ; // https://msdn.microsoft.com/en-us/library/ms191472.aspx join_part // https://msdn.microsoft.com/en-us/library/ms173815(v=sql.120).aspx : (INNER? | join_type=(LEFT | RIGHT | FULL) OUTER?) (join_hint=(LOOP | HASH | MERGE | REMOTE | SEMI))? JOIN table_source ON search_condition | CROSS JOIN table_source | CROSS APPLY table_source | OUTER APPLY table_source | LATERAL VIEW lateral_view_function table_alias? (AS? column_alias)? ; table_name_with_hint : table_name with_table_hints? ; // https://msdn.microsoft.com/en-us/library/ms190312.aspx rowset_function : OPENROWSET '(' BULK data_file=STRING ',' (bulk_option (',' bulk_option)* | id)')' ; // runtime check. bulk_option : id '=' (DECIMAL | STRING) ; derived_table : '(' subquery ')' | table_value_constructor ; function_call : ranking_windowed_function | value_manipulation_function | aggregate_windowed_function ; datepart : ID ; as_table_alias : AS? table_alias ; table_alias : id with_table_hints? ; // https://msdn.microsoft.com/en-us/library/ms187373.aspx with_table_hints : WITH? '(' table_hint (',' table_hint)* ')' ; // Id runtime check. Id can be (FORCESCAN, HOLDLOCK, NOLOCK, NOWAIT, PAGLOCK, READCOMMITTED, // READCOMMITTEDLOCK, READPAST, READUNCOMMITTED, REPEATABLEREAD, ROWLOCK, TABLOCK, TABLOCKX // UPDLOCK, XLOCK) table_hint : NOEXPAND? ( INDEX '(' index_value (',' index_value)* ')' | INDEX '=' index_value | FORCESEEK ('(' index_value '(' index_column_name (',' index_column_name)* ')' ')')? | SERIALIZABLE | SNAPSHOT | SPATIAL_WINDOW_MAX_CELLS '=' DECIMAL | ID)? ; index_column_name : ID ; index_value : ID | DECIMAL ; column_alias_list : '(' column_alias (',' column_alias)* ')' ; column_alias : id | STRING ; table_value_constructor : VALUES '(' expression_list ')' (',' '(' expression_list ')')* ; expression_list : expression (',' expression)* ; // https://msdn.microsoft.com/en-us/library/ms181765.aspx case_expr : CASE expression (WHEN expression THEN expression)+ (ELSE expression)? END | CASE (WHEN search_condition THEN expression)+ (ELSE expression)? END ; // https://msdn.microsoft.com/en-us/library/ms189798.aspx ranking_windowed_function : RANK '(' ')' over_clause | DENSE_RANK '(' ')' over_clause | NTILE '(' expression ')' over_clause | ROW_NUMBER '(' ')' over_clause ; value_manipulation_function : unary_manipulation_function | noparam_manipulation_function | binary_manipulation_function | ternary_manipulation_function | nary_manipulation_function | extract_time_function ; nary_manipulation_function : function_name=(CONCAT | CONCAT_WS | COALESCE) '(' expression (',' expression)* ')' ; ternary_manipulation_function : function_name=(CONV | SUBSTR | HASH | RPAD) '(' expression ',' expression ',' expression ')' ; binary_manipulation_function : function_name=(ROUND | MOD | PMOD | STRTOL | POW | PERCENTILE | SPLIT | INSTR | ENCODE | DECODE | SHIFTLEFT | SHIFTRIGHT | SHIFTRIGHTUNSIGNED | NVL | FIND_IN_SET | FORMAT_NUMBER | GET_JSON_OBJECT | IN_FILE | LOCATE | REPEAT | AES_ENCRYPT | AES_DECRYPT) '(' expression ',' expression ')' ; extract_time_function : function_name=EXTRACT '(' extract_unit FROM expression ')' ; extract_unit : YEAR | expression ; unary_manipulation_function : function_name=(ROUND | FLOOR | CEIL | EXP | LN | LOG10 | LOG2 | SIN | COS | TAN | SIGN | RAND | FNV_HASH | RAWTOHEX | ABS | STDDEV | SQRT | MD5 | CRC32 | YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE | SECOND | WEEKOFYEAR | LOWER | UPPER | ASCII | CHARACTER_LENGTH | FACTORIAL | CBRT | LENGTH | TRIM | ASIN | ACOS | ATAN | DEGREES | RADIANS | POSITIVE | NEGATIVE | BROUND | BIN | HEX | UNHEX | FROM_UNIXTIME | TO_DATE | CHR | LTRIM | REVERSE | SPACE_FUNCTION | SHA1 | SHA2 ) '(' expression ')' | function_name=CAST '(' cast_as_expression ')' ; noparam_manipulation_function : function_name=(UNIX_TIMESTAMP | CURRENT_TIMESTAMP | RANDOM | NATURAL_CONSTANT | PI) '(' ')' ; lateral_view_function : function_name=EXPLODE '(' expression ')' ; // https://msdn.microsoft.com/en-us/library/ms173454.aspx aggregate_windowed_function : AVG '(' all_distinct_expression ')' over_clause? | CHECKSUM_AGG '(' all_distinct_expression ')' | GROUPING '(' expression ')' | GROUPING_ID '(' expression_list ')' | MAX '(' all_distinct_expression ')' over_clause? | MIN '(' all_distinct_expression ')' over_clause? | SUM '(' all_distinct_expression ')' over_clause? | STDEV '(' all_distinct_expression ')' over_clause? | STDEVP '(' all_distinct_expression ')' over_clause? | STDDEV_SAMP '(' all_distinct_expression ')' over_clause? | VAR '(' all_distinct_expression ')' over_clause? | VARP '(' all_distinct_expression ')' over_clause? | COUNT '(' ('*' | all_distinct_expression) ')' over_clause? | NDV '(' all_distinct_expression ')' over_clause? | COUNT_BIG '(' ('*' | all_distinct_expression) ')' over_clause? ; all_distinct_expression : (ALL | DISTINCT)? expression ; cast_as_expression : expression AS data_type ; // https://msdn.microsoft.com/en-us/library/ms189461.aspx over_clause : OVER '(' partition_by_clause? order_by_clause? row_or_range_clause? ')' ; row_or_range_clause : (ROWS | RANGE) window_frame_extent ; window_frame_extent : window_frame_preceding | BETWEEN window_frame_bound AND window_frame_bound ; window_frame_bound : window_frame_preceding | window_frame_following ; window_frame_preceding : UNBOUNDED PRECEDING | DECIMAL PRECEDING | CURRENT ROW ; window_frame_following : UNBOUNDED FOLLOWING | DECIMAL FOLLOWING ; // Primitive. full_table_name : (server=id '.' database=id '.' schema=id '.' | database=id '.' (schema=id)? '.' | schema=id '.')? table=id ; table_name : (database=id '.' (schema=id)? '.' | schema=id '.')? table=id ; view_name : (schema=id '.')? view=id ; func_proc_name : (database=id '.' (schema=id)? '.' | (schema=id) '.')? procedure=id ; ddl_object : full_table_name | LOCAL_ID ; full_column_name : (table_name '.')? column_name ; column_name_list : column_name (',' column_name)* ; column_name : id ; cursor_name : id | LOCAL_ID ; on_off : ON | OFF ; clustered : CLUSTERED | NONCLUSTERED ; null_notnull : NOT? NULL ; true_orfalse : TRUE | FALSE ; scalar_function_name : func_proc_name | RIGHT | LEFT | BINARY_CHECKSUM | CHECKSUM ; // https://msdn.microsoft.com/en-us/library/ms187752.aspx // TODO: implement runtime check or add new tokens. data_type /* : BIGINT | BINARY '(' DECIMAL ')' | BIT | CHAR '(' DECIMAL ')' | DATE | DATETIME | DATETIME2 | DATETIMEOFFSET '(' DECIMAL ')' | DECIMAL '(' DECIMAL ',' DECIMAL ')' | DOUBLE | FLOAT | GEOGRAPHY | GEOMETRY | HIERARCHYID | IMAGE | INT | MONEY | NCHAR '(' DECIMAL ')' | NTEXT | NUMERIC '(' DECIMAL ',' DECIMAL ')' | NVARCHAR '(' DECIMAL | MAX ')' | REAL | SMALLDATETIME | SMALLINT | SMALLMONEY | SQL_VARIANT | TEXT | TIME '(' DECIMAL ')' | TIMESTAMP | TINYINT | UNIQUEIDENTIFIER | VARBINARY '(' DECIMAL | MAX ')' | VARCHAR '(' DECIMAL | MAX ')' | XML */ : id IDENTITY? ('(' (DECIMAL | MAX) (',' DECIMAL)? ')')? ; default_value : NULL | constant ; // https://msdn.microsoft.com/en-us/library/ms179899.aspx constant : STRING // string, datetime or uniqueidentifier | BINARY | number | sign? (REAL | FLOAT) // float or decimal | sign? '$' (DECIMAL | FLOAT) // money ; number : sign? DECIMAL ; sign : PLUS | MINUS ; // https://msdn.microsoft.com/en-us/library/ms175874.aspx id : simple_id | DOUBLE_QUOTE_ID | SQUARE_BRACKET_ID | BACKTICK_ID ; simple_id : ID | ABSOLUTE | APPLY | AUTO | AVG | BASE64 | CALLER | CAST | CATCH | CHECKSUM_AGG | COMMITTED | CONCAT | CONCAT_WS | COOKIE | COUNT | COUNT_BIG | DELAY | DELETED | DENSE_RANK | DISABLE | DYNAMIC | ENCRYPTION | EXTRACT | FAST | FAST_FORWARD | FIRST | FOLLOWING | FORCESEEK | FORWARD_ONLY | FULLSCAN | GLOBAL | GO | GROUPING | GROUPING_ID | HASH | INSENSITIVE | INSERTED | ISOLATION | KEYSET | KEEPFIXED | LAST | LEVEL | LOCAL | LOCK_ESCALATION | LOGIN | LOOP | MARK | MAX | MIN | MODIFY | NAME | NEXT | NOCOUNT | NOEXPAND | NORECOMPUTE | NTILE | NUMBER | OFFSET | ONLY | OPTIMISTIC | OPTIMIZE | OUT | OUTPUT | OWNER | PARTITION | PATH | PRECEDING | PRIOR | RANGE | RANK | READONLY | READ_ONLY | RECOMPILE | RELATIVE | REMOTE | REPEATABLE | ROOT | ROW | ROWGUID | ROWS | ROW_NUMBER | SAMPLE | SCHEMABINDING | SCROLL | SCROLL_LOCKS | SELF | SERIALIZABLE | SNAPSHOT | SPATIAL_WINDOW_MAX_CELLS | STATIC | STATS_STREAM | STDEV | STDEVP | STDDEV_SAMP | STRTOL | SUM | THROW | TIES | TIME | TRY | TYPE | TYPE_WARNING | UNBOUNDED | UNCOMMITTED | UNKNOWN | USING | VAR | VARP | VIEW_METADATA | WORK | XML | XMLNAMESPACES | DAY | MONTH | YEAR | DAYS | MONTHS | YEARS | STORE | INTERVAL | TABLES | COLUMNS ; // https://msdn.microsoft.com/en-us/library/ms188074.aspx // Spaces are allowed for comparison operators. comparison_operator : '=' | '>' | '<' | '<=' | '>=' | '<>' | '!=' | '!>' | '!<' | '<' '=' | '>' '=' | '<' '>' | '!' '=' | '!' '>' | '!' '<' ; assignment_operator : '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '^=' | '|=' ; // Lexer // Basic keywords (from https://msdn.microsoft.com/en-us/library/ms189822.aspx) ADD: A D D; ALL: A L L; ALTER: A L T E R; AND: A N D; ANY: A N Y; AS: A S; ASC: A S C; ASCII: A S C I I; AUTHORIZATION: A U T H O R I Z A T I O N; BACKUP: B A C K U P; BEGIN: B E G I N; BETWEEN: B E T W E E N; BREAK: B R E A K; BROWSE: B R O W S E; BULK: B U L K; BY: B Y; CASCADE: C A S C A D E; CASE: C A S E; CHANGETABLE: C H A N G E T A B L E; CHANGES: C H A N G E S; CHECK: C H E C K; CHECKPOINT: C H E C K P O I N T; CLOSE: C L O S E; CLUSTERED: C L U S T E R E D; COALESCE: C O A L E S C E; COLLATE: C O L L A T E; COLUMN: C O L U M N; COMMIT: C O M M I T; COMPUTE: C O M P U T E; CONSTRAINT: C O N S T R A I N T; CONTAINS: C O N T A I N S; CONTAINSTABLE: C O N T A I N S T A B L E; CONTINUE: C O N T I N U E; CONV: C O N V; CONVERT: C O N V E R T; CREATE: C R E A T E; CROSS: C R O S S; CURRENT: C U R R E N T; CURRENT_DATE: C U R R E N T '_' D A T E; CURRENT_TIME: C U R R E N T '_' T I M E; CURRENT_TIMESTAMP: C U R R E N T '_' T I M E S T A M P; CURRENT_USER: C U R R E N T '_' U S E R; CURSOR: C U R S O R; DATABASE: D A T A B A S E; DATABASES: D A T A B A S E S; DBCC: D B C C; DEALLOCATE: D E A L L O C A T E; DECLARE: D E C L A R E; DELETE: D E L E T E; DENY: D E N Y; DESC: D E S C; DESCRIBE: D E S C R I B E; DISK: D I S K; DISTINCT: D I S T I N C T; DISTRIBUTED: D I S T R I B U T E D; DOUBLE: D O U B L E; DROP: D R O P; DUMP: D U M P; ELSE: E L S E; END: E N D; ERRLVL: E R R L V L; ESCAPE: E S C A P E; EXCEPT: E X C E P T; EXEC: E X E C; EXECUTE: E X E C U T E; EXISTS: E X I S T S; EXIT: E X I T; EXTERNAL: E X T E R N A L; FALSE: F A L S E; FETCH: F E T C H; FILE: F I L E; FILLFACTOR: F I L L F A C T O R; FOR: F O R; FORCESEEK: F O R C E S E E K; FOREIGN: F O R E I G N; FREETEXT: F R E E T E X T; FREETEXTTABLE: F R E E T E X T T A B L E; FROM: F R O M; FULL: F U L L; FUNCTION: F U N C T I O N; GOTO: G O T O; GRANT: G R A N T; GROUP: G R O U P; HASH: H A S H; HAVING: H A V I N G; IDENTITY: I D E N T I T Y; IDENTITYCOL: I D E N T I T Y C O L; IDENTITY_INSERT: I D E N T I T Y '_' I N S E R T; IF: I F; IN: I N; INDEX: I N D E X; INNER: I N N E R; INSERT: I N S E R T; INTERSECT: I N T E R S E C T; INTO: I N T O; IS: I S; JOIN: J O I N; KEY: K E Y; KILL: K I L L; LEFT: L E F T; LIKE: L I K E; LIMIT: L I M I T; LINENO: L I N E N O; LOAD: L O A D; MERGE: M E R G E; NATIONAL: N A T I O N A L; NOCHECK: N O C H E C K; NONCLUSTERED: N O N C L U S T E R E D; NOT: N O T; NULL: N U L L; NULLIF: N U L L I F; OF: O F; OFF: O F F; OFFSETS: O F F S E T S; ON: O N; OPEN: O P E N; OPENDATASOURCE: O P E N D A T A S O U R C E; OPENQUERY: O P E N Q U E R Y; OPENROWSET: O P E N R O W S E T; OPENXML: O P E N X M L; OPTION: O P T I O N; OR: O R; ORDER: O R D E R; OUTER: O U T E R; OVER: O V E R; PERCENT: P E R C E N T; PIVOT: P I V O T; PLAN: P L A N; PRECISION: P R E C I S I O N; PRIMARY: P R I M A R Y; PRINT: P R I N T; PROC: P R O C; PROCEDURE: P R O C E D U R E; RAISERROR: R A I S E R R O R; RAWTOHEX: R A W T O H E X; READ: R E A D; READTEXT: R E A D T E X T; RECONFIGURE: R E C O N F I G U R E; REFERENCES: R E F E R E N C E S; REPLICATION: R E P L I C A T I O N; RESTORE: R E S T O R E; RESTRICT: R E S T R I C T; RETURN: R E T U R N; REVERT: R E V E R T; REVOKE: R E V O K E; RIGHT: R I G H T; ROLLBACK: R O L L B A C K; ROWCOUNT: R O W C O U N T; ROWGUIDCOL: R O W G U I D C O L; RPAD: R P A D; RULE: R U L E; SAVE: S A V E; SCHEMA: S C H E M A; SCHEMAS: S C H E M A S; SECURITYAUDIT: S E C U R I T Y A U D I T; SELECT: S E L E C T; SEMANTICKEYPHRASETABLE: S E M A N T I C K E Y P H R A S E T A B L E; SEMANTICSIMILARITYDETAILSTABLE: S E M A N T I C S I M I L A R I T Y D E T A I L S T A B L E; SEMANTICSIMILARITYTABLE: S E M A N T I C S I M I L A R I T Y T A B L E; SEMI: S E M I; SESSION_USER: S E S S I O N '_' U S E R; SET: S E T; SETUSER: S E T U S E R; SHUTDOWN: S H U T D O W N; SOME: S O M E; SUBSTR: S U B S T R; STATISTICS: S T A T I S T I C S; SYSTEM_USER: S Y S T E M '_' U S E R; TABLE: T A B L E; TABLES: T A B L E S; TABLESAMPLE: T A B L E S A M P L E; TEXTSIZE: T E X T S I Z E; THEN: T H E N; TO: T O; TOP: T O P; TRAN: T R A N; TRANSACTION: T R A N S A C T I O N; TRIGGER: T R I G G E R; TRUE: T R U E; TRUNCATE: T R U N C A T E; TRY_CONVERT: T R Y '_' C O N V E R T; TSEQUAL: T S E Q U A L; UNION: U N I O N; UNIQUE: U N I Q U E; UNPIVOT: U N P I V O T; UPDATE: U P D A T E; UPDATETEXT: U P D A T E T E X T; USE: U S E; USER: U S E R; VALUES: V A L U E S; VARYING: V A R Y I N G; VIEW: V I E W; WAITFOR: W A I T F O R; WHEN: W H E N; WHERE: W H E R E; WHILE: W H I L E; WITH: W I T H; WITHIN: W I T H I N; WRITETEXT: W R I T E T E X T; // Additional keywords (they can be id). ABSOLUTE: A B S O L U T E; ABS: A B S; ACOS: A C O S; AES_DECRYPT: A E S '_' D E C R Y P T; AES_ENCRYPT: A E S '_' E N C R Y P T; APPLY: A P P L Y; ASIN: A S I N; ATAN: A T A N; AUTO: A U T O; AVG: A V G; BASE64: B A S E '64'; BIN: B I N; BINARY_CHECKSUM: B I N A R Y '_' C H E C K S U M; BROUND: B R O U N D; CALLER: C A L L E R; CAST: C A S T; CATCH: C A T C H; CBRT: C B R T; CEIL: C E I L; CHARACTER_LENGTH: C H A R A C T E R '_' L E N G T H; CHECKSUM: C H E C K S U M; CHECKSUM_AGG: C H E C K S U M '_' A G G; CHR: C H R; COMMITTED: C O M M I T T E D; CONCAT: C O N C A T; CONCAT_WS: C O N C A T '_' W S; CONFIG: C O N F I G; COOKIE: C O O K I E; COS: C O S; COUNT: C O U N T; COUNT_BIG: C O U N T '_' B I G; CRC32: C R C '32'; DATEADD: D A T E A D D; DATEDIFF: D A T E D I F F; DATENAME: D A T E N A M E; DATEPART: D A T E P A R T; DAY: D A Y; DAYS: D A Y S; DECODE: D E C O D E; DEGREES: D E G R E E S; DELAY: D E L A Y; DELETED: D E L E T E D; DENSE_RANK: D E N S E '_' R A N K; DISABLE: D I S A B L E; DYNAMIC: D Y N A M I C; NATURAL_CONSTANT: E; ENCODE: E N C O D E; ENCRYPTION: E N C R Y P T I O N; ESCAPED_BY: E S C A P E D ' ' B Y; EXACT: E X A C T; EXP: E X P; EXPLODE: E X P L O D E; EXTRACT: E X T R A C T; FACTORIAL: F A C T O R I A L; FAST: F A S T; FAST_FORWARD: F A S T '_' F O R W A R D; FIELDS_SEPARATED_BY: F I E L D S ' ' S E P A R A T E D ' ' B Y; FIND_IN_SET: F I N D '_' I N '_' S E T; FIRST: F I R S T; FLOOR: F L O O R; FOLLOWING: F O L L O W I N G; FORMAT_NUMBER: F O R M A T '_' N U M B E R; FORWARD_ONLY: F O R W A R D '_' O N L Y; FNV_HASH: F N V '_' H A S H; FROM_UNIXTIME: F R O M '_' U N I X T I M E; FULLSCAN: F U L L S C A N; GET_JSON_OBJECT: G E T '_' J S O N '_' O B J E C T; GLOBAL: G L O B A L; GO: G O; GROUPING: G R O U P I N G; GROUPING_ID: G R O U P I N G '_' I D; HEX: H E X; HOUR: H O U R; INSENSITIVE: I N S E N S I T I V E; INSERTED: I N S E R T E D; INSTR: I N S T R; INTERVAL: I N T E R V A L; IN_FILE: I N '_' F I L E; ISOLATION: I S O L A T I O N; KEEPFIXED: K E E P F I X E D; KEYSET: K E Y S E T; LAST: L A S T; LATERAL: L A T E R A L; LENGTH: L E N G T H; LEVEL: L E V E L; LN: L N; LOCAL: L O C A L; LOCATE: L O C A T E; LOCATION: L O C A T I O N; LOCK_ESCALATION: L O C K '_' E S C A L A T I O N; LOG2: L O G '2'; LOG10: L O G '10'; LOGIN: L O G I N; LOOP: L O O P; LOWER: L O W E R; LTRIM: L T R I M; MARK: M A R K; MAX: M A X; MD5: M D '5'; MIN: M I N; MIN_ACTIVE_ROWVERSION: M I N '_' A C T I V E '_' R O W V E R S I O N; MINUTE: M I N U T E; MOD: M O D; MODIFY: M O D I F Y; MONTH: M O N T H; MONTHS: M O N T H S; NEGATIVE: N E G A T I V E; NEXT: N E X T; NAME: N A M E; NDV: N D V; NOCOUNT: N O C O U N T; NOEXPAND: N O E X P A N D; NORECOMPUTE: N O R E C O M P U T E; NTILE: N T I L E; NUMBER: N U M B E R; NVL: N V L; OFFSET: O F F S E T; ONLY: O N L Y; OPTIMISTIC: O P T I M I S T I C; OPTIMIZE: O P T I M I Z E; OUT: O U T; OUTPUT: O U T P U T; OWNER: O W N E R; PARTITION: P A R T I T I O N; PATH: P A T H; PERCENTILE: P E R C E N T I L E; PI: P I; PMOD: P M O D; POSITIVE: P O S I T I V E; POW: P O W; PRECEDING: P R E C E D I N G; PRIOR: P R I O R; QUARTER: Q U A R T E R; QUOTED_BY: Q U O T E D ' ' B Y; RADIANS: R A D I A N S; RAND: R A N D; RANDOM: R A N D O M; RANGE: R A N G E; RANK: R A N K; READONLY: R E A D O N L Y; READ_ONLY: R E A D '_' O N L Y; RECOMMENDED: R E C O M M E N D E D; RECOMPILE: R E C O M P I L E; REFRESH: R E F R E S H; RELATIVE: R E L A T I V E; REMOTE: R E M O T E; REPEAT: R E P E A T; REPEATABLE: R E P E A T A B L E; REVERSE: R E V E R S E; ROLLUP: R O L L U P; ROOT: R O O T; ROUND: R O U N D; ROW: R O W; ROWGUID: R O W G U I D; ROWS: R O W S; ROW_NUMBER: R O W '_' N U M B E R; SAMPLE: S A M P L E; SCHEMABINDING: S C H E M A B I N D I N G; SCROLL: S C R O L L; SCROLL_LOCKS: S C R O L L '_' L O C K S; SECOND: S E C O N D; SELF: S E L F; SERIALIZABLE: S E R I A L I Z A B L E; SHA1: S H A '1'; SHA2: S H A '2'; SHIFTLEFT: S H I F T L E F T; SHIFTRIGHT: S H I F T R I G H T; SHIFTRIGHTUNSIGNED: S H I F T R I G H T U N S I G N E D; SIGN: S I G N; SIN: S I N; SNAPSHOT: S N A P S H O T; SPACE_FUNCTION: S P A C E; SPATIAL_WINDOW_MAX_CELLS: S P A T I A L '_' W I N D O W '_' M A X '_' C E L L S; SPLIT: S P L I T; STATIC: S T A T I C; STATS_STREAM: S T A T S '_' S T R E A M; STDEV: S T D E V; STDDEV: S T D D E V; STDEVP: S T D E V P; STDDEV_SAMP: S T D D E V '_' S A M P; STORED_AS_PARQUET: S T O R E D ' ' A S ' ' P A R Q U E T; SUM: S U M; SQRT: S Q R T; STRTOL: S T R T O L; TAN: T A N; THROW: T H R O W; TIES: T I E S; TIME: T I M E; TO_DATE: T O '_' D A T E; TRIM: T R I M; TRY: T R Y; TYPE: T Y P E; TYPE_WARNING: T Y P E '_' W A R N I N G; UNBOUNDED: U N B O U N D E D; UNCOMMITTED: U N C O M M I T T E D; UNHEX: U N H E X; UNIVERSE: U N I V E R S E; UNIX_TIMESTAMP: U N I X '_' T I M E S T A M P; UNKNOWN: U N K N O W N; UPPER: U P P E R; USING: U S I N G; VAR: V A R; VARP: V A R P; VIEW_METADATA: V I E W '_' M E T A D A T A; WEEKOFYEAR: W E E K O F Y E A R; WORK: W O R K; XML: X M L; XMLNAMESPACES: X M L N A M E S P A C E S; YEAR: Y E A R; YEARS: Y E A R S; DOLLAR_ACTION: '$' A C T I O N; SPACE: [ \\t\\r\\n]+ -> channel(1); COMMENT: '/*' .*? '*/' -> channel(HIDDEN); LINE_COMMENT: '--' ~[\\r\\n]* -> channel(HIDDEN); // TODO: ID can be not only Latin. DOUBLE_QUOTE_ID: '""' ~'""'+ '""'; BACKTICK_ID: '`' ~'`'+ '`'; SQUARE_BRACKET_ID: '[' ~']'+ ']'; LOCAL_ID: '@' [a-zA-Z_$@#0-9]+; DECIMAL: DEC_DIGIT+; ID: [a-zA-Z_#][a-zA-Z_#$@0-9]*; STRING: N? '\\'' (~'\\'' | '\\'\\'')* '\\''; BINARY: '0' X HEX_DIGIT*; FLOAT: DEC_DOT_DEC; REAL: DEC_DOT_DEC (E [+-]? DEC_DIGIT+)?; EQUAL: '='; GREATER: '>'; LESS: '<'; EXCLAMATION: '!'; PLUS_ASSIGN: '+='; MINUS_ASSIGN: '-='; MULT_ASSIGN: '*='; DIV_ASSIGN: '/='; MOD_ASSIGN: '%='; AND_ASSIGN: '&='; XOR_ASSIGN: '^='; OR_ASSIGN: '|='; DOT: '.'; UNDERLINE: '_'; AT: '@'; SHARP: '#'; DOLLAR: '$'; LR_BRACKET: '('; RR_BRACKET: ')'; COMMA: ','; SEMICOLON: ';'; COLON: ':'; STAR: '*'; DIVIDE: '/'; MODULE: '%'; PLUS: '+'; MINUS: '-'; BIT_NOT: '~'; BIT_OR: '|'; BIT_AND: '&'; BIT_XOR: '^'; fragment LETTER: [a-zA-Z_]; fragment DEC_DOT_DEC: (DEC_DIGIT+ '.' DEC_DIGIT+ | DEC_DIGIT+ '.' | '.' DEC_DIGIT+); fragment HEX_DIGIT: [0-9A-Fa-f]; fragment DEC_DIGIT: [0-9]; fragment A: [aA]; fragment B: [bB]; fragment C: [cC]; fragment D: [dD]; fragment E: [eE]; fragment F: [fF]; fragment G: [gG]; fragment H: [hH]; fragment I: [iI]; fragment J: [jJ]; fragment K: [kK]; fragment L: [lL]; fragment M: [mM]; fragment N: [nN]; fragment O: [oO]; fragment P: [pP]; fragment Q: [qQ]; fragment R: [rR]; fragment S: [sS]; fragment T: [tT]; fragment U: [uU]; fragment V: [vV]; fragment W: [wW]; fragment X: [xX]; fragment Y: [yY]; fragment Z: [zZ]; ",12265,False,2433.1214637797816,median "[[production-ready]] = Spring Boot Actuator: Production-ready features [partintro] -- Spring Boot includes a number of additional features to help you monitor and manage your application when you push it to production. You can choose to manage and monitor your application by using HTTP endpoints or with JMX. Auditing, health, and metrics gathering can also be automatically applied to your application. -- [[production-ready-enabling]] == Enabling Production-ready Features The {github-code}/spring-boot-project/spring-boot-actuator[`spring-boot-actuator`] module provides all of Spring Boot's production-ready features. The simplest way to enable the features is to add a dependency to the `spring-boot-starter-actuator` '`Starter`'. .Definition of Actuator **** An actuator is a manufacturing term that refers to a mechanical device for moving or controlling something. Actuators can generate a large amount of motion from a small change. **** To add the actuator to a Maven based project, add the following '`Starter`' dependency: [source,xml,indent=0] ---- org.springframework.boot spring-boot-starter-actuator ---- For Gradle, use the following declaration: [source,groovy,indent=0] ---- dependencies { compile(""org.springframework.boot:spring-boot-starter-actuator"") } ---- [[production-ready-endpoints]] == Endpoints Actuator endpoints let you monitor and interact with your application. Spring Boot includes a number of built-in endpoints and lets you add your own. For example, the `health` endpoint provides basic application health information. Each individual endpoint can be <>. This controls whether or not the endpoint is created and its bean exists in the application context. To be remotely accessible an endpoint also has to be <>. Most applications choose HTTP, where the ID of the endpoint along with a prefix of `/actuator` is mapped to a URL. For example, by default, the `health` endpoint is mapped to `/actuator/health`. The following technology-agnostic endpoints are available: [cols=""2,5,2""] |=== | ID | Description | Enabled by default |`auditevents` |Exposes audit events information for the current application. |Yes |`beans` |Displays a complete list of all the Spring beans in your application. |Yes |`caches` |Exposes available caches. |Yes |`conditions` |Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match. |Yes |`configprops` |Displays a collated list of all `@ConfigurationProperties`. |Yes |`env` |Exposes properties from Spring's `ConfigurableEnvironment`. |Yes |`flyway` |Shows any Flyway database migrations that have been applied. |Yes |`health` |Shows application health information. |Yes |`httptrace` |Displays HTTP trace information (by default, the last 100 HTTP request-response exchanges). |Yes |`info` |Displays arbitrary application info. |Yes |`integrationgraph` |Shows the Spring Integration graph. |Yes |`loggers` |Shows and modifies the configuration of loggers in the application. |Yes |`liquibase` |Shows any Liquibase database migrations that have been applied. |Yes |`metrics` |Shows '`metrics`' information for the current application. |Yes |`mappings` |Displays a collated list of all `@RequestMapping` paths. |Yes |`scheduledtasks` |Displays the scheduled tasks in your application. |Yes |`sessions` |Allows retrieval and deletion of user sessions from a Spring Session-backed session store. Not available when using Spring Session's support for reactive web applications. |Yes |`shutdown` |Lets the application be gracefully shutdown. |No |`threaddump` |Performs a thread dump. |Yes |=== If your application is a web application (Spring MVC, Spring WebFlux, or Jersey), you can use the following additional endpoints: [cols=""2,5,2""] |=== | ID | Description | Enabled by default |`heapdump` |Returns a GZip compressed `hprof` heap dump file. |Yes |`jolokia` |Exposes JMX beans over HTTP (when Jolokia is on the classpath, not available for WebFlux). |Yes |`logfile` |Returns the contents of the logfile (if `logging.file` or `logging.path` properties have been set). Supports the use of the HTTP `Range` header to retrieve part of the log file's content. |Yes |`prometheus` |Exposes metrics in a format that can be scraped by a Prometheus server. |Yes |=== To learn more about the Actuator's endpoints and their request and response formats, please refer to the separate API documentation ({spring-boot-actuator-api}/html[HTML] or {spring-boot-actuator-api}/pdf/spring-boot-actuator-web-api.pdf[PDF]). [[production-ready-endpoints-enabling-endpoints]] === Enabling Endpoints By default, all endpoints except for `shutdown` are enabled. To configure the enablement of an endpoint, use its `management.endpoint..enabled` property. The following example enables the `shutdown` endpoint: [source,properties,indent=0] ---- management.endpoint.shutdown.enabled=true ---- If you prefer endpoint enablement to be opt-in rather than opt-out, set the `management.endpoints.enabled-by-default` property to `false` and use individual endpoint `enabled` properties to opt back in. The following example enables the `info` endpoint and disables all other endpoints: [source,properties,indent=0] ---- management.endpoints.enabled-by-default=false management.endpoint.info.enabled=true ---- NOTE: Disabled endpoints are removed entirely from the application context. If you want to change only the technologies over which an endpoint is exposed, use the <> instead. [[production-ready-endpoints-exposing-endpoints]] === Exposing Endpoints Since Endpoints may contain sensitive information, careful consideration should be given about when to expose them. The following table shows the default exposure for the built-in endpoints: [cols=""1,1,1""] |=== | ID | JMX | Web |`auditevents` |Yes |No |`beans` |Yes |No |`conditions` |Yes |No |`configprops` |Yes |No |`env` |Yes |No |`flyway` |Yes |No |`health` |Yes |Yes |`heapdump` |N/A |No |`httptrace` |Yes |No |`info` |Yes |Yes |`integrationgraph` |Yes |Yes |`jolokia` |N/A |No |`logfile` |N/A |No |`loggers` |Yes |No |`liquibase` |Yes |No |`metrics` |Yes |No |`mappings` |Yes |No |`prometheus` |N/A |No |`scheduledtasks` |Yes |No |`sessions` |Yes |No |`shutdown` |Yes |No |`threaddump` |Yes |No |=== To change which endpoints are exposed, use the following technology-specific `include` and `exclude` properties: [cols=""3,1""] |=== |Property | Default |`management.endpoints.jmx.exposure.exclude` | |`management.endpoints.jmx.exposure.include` | `*` |`management.endpoints.web.exposure.exclude` | |`management.endpoints.web.exposure.include` | `info, health` |=== The `include` property lists the IDs of the endpoints that are exposed. The `exclude` property lists the IDs of the endpoints that should not be exposed. The `exclude` property takes precedence over the `include` property. Both `include` and `exclude` properties can be configured with a list of endpoint IDs. For example, to stop exposing all endpoints over JMX and only expose the `health` and `info` endpoints, use the following property: [source,properties,indent=0] ---- management.endpoints.jmx.exposure.include=health,info ---- `*` can be used to select all endpoints. For example, to expose everything over HTTP except the `env` and `beans` endpoints, use the following properties: [source,properties,indent=0] ---- management.endpoints.web.exposure.include=* management.endpoints.web.exposure.exclude=env,beans ---- [NOTE] ==== `*` has a special meaning in YAML, so be sure to add quotes if you want to include (or exclude) all endpoints, as shown in the following example: [source,yaml,indent=0] ---- management: endpoints: web: exposure: include: ""*"" ---- ==== NOTE: If your application is exposed publicly, we strongly recommend that you also <>. TIP: If you want to implement your own strategy for when endpoints are exposed, you can register an `EndpointFilter` bean. [[production-ready-endpoints-security]] === Securing HTTP Endpoints You should take care to secure HTTP endpoints in the same way that you would any other sensitive URL. If Spring Security is present, endpoints are secured by default using Spring Security’s content-negotiation strategy. If you wish to configure custom security for HTTP endpoints, for example, only allow users with a certain role to access them, Spring Boot provides some convenient `RequestMatcher` objects that can be used in combination with Spring Security. A typical Spring Security configuration might look something like the following example: [source,java,indent=0] ---- @Configuration public class ActuatorSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests() .anyRequest().hasRole(""ENDPOINT_ADMIN"") .and() .httpBasic(); } } ---- The preceding example uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint and then ensures that all have the `ENDPOINT_ADMIN` role. Several other matcher methods are also available on `EndpointRequest`. See the API documentation ({spring-boot-actuator-api}/html[HTML] or {spring-boot-actuator-api}/pdf/spring-boot-actuator-web-api.pdf[PDF]) for details. If you deploy applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication. You can do so by changing the `management.endpoints.web.exposure.include` property, as follows: .application.properties [source,properties,indent=0] ---- management.endpoints.web.exposure.include=* ---- Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints as shown in the following example: [source,java,indent=0] ---- @Configuration public class ActuatorSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.requestMatcher(EndpointRequest.toAnyEndpoint()).authorizeRequests() .anyRequest().permitAll(); } } ---- [[production-ready-endpoints-caching]] === Configuring Endpoints Endpoints automatically cache responses to read operations that do not take any parameters. To configure the amount of time for which an endpoint will cache a response, use its `cache.time-to-live` property. The following example sets the time-to-live of the `beans` endpoint's cache to 10 seconds: .application.properties [source,properties,indent=0] ---- management.endpoint.beans.cache.time-to-live=10s ---- NOTE: The prefix `management.endpoint.` is used to uniquely identify the endpoint that is being configured. NOTE: When making an authenticated HTTP request, the `Principal` is considered as input to the endpoint and, therefore, the response will not be cached. [[production-ready-endpoints-hypermedia]] === Hypermedia for Actuator Web Endpoints A ""`discovery page`"" is added with links to all the endpoints. The ""`discovery page`"" is available on `/actuator` by default. When a custom management context path is configured, the ""`discovery page`"" automatically moves from `/actuator` to the root of the management context. For example, if the management context path is `/management`, then the discovery page is available from `/management`. When the management context path is set to `/`, the discovery page is disabled to prevent the possibility of a clash with other mappings. [[production-ready-endpoints-custom-mapping]] === Actuator Web Endpoint Paths By default, endpoints are exposed over HTTP under the `/actuator` path by using the ID of the endpoint. For example, the `beans` endpoint is exposed under `/actuator/beans`. If you want to map endpoints to a different path, you can use the `management.endpoints.web.path-mapping` property. Also, if you want change the base path, you can use `management.endpoints.web.base-path`. The following example remaps `/actuator/health` to `/healthcheck`: .application.properties [source,properties,indent=0] ---- management.endpoints.web.base-path=/ management.endpoints.web.path-mapping.health=healthcheck ---- [[production-ready-endpoints-cors]] === CORS Support https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] (CORS) is a https://www.w3.org/TR/cors/[W3C specification] that lets you specify in a flexible way what kind of cross-domain requests are authorized. If you use Spring MVC or Spring WebFlux, Actuator's web endpoints can be configured to support such scenarios. CORS support is disabled by default and is only enabled once the `management.endpoints.web.cors.allowed-origins` property has been set. The following configuration permits `GET` and `POST` calls from the `example.com` domain: [source,properties,indent=0] ---- management.endpoints.web.cors.allowed-origins=http://example.com management.endpoints.web.cors.allowed-methods=GET,POST ---- TIP: See {sc-spring-boot-actuator-autoconfigure}/endpoint/web/CorsEndpointProperties.{sc-ext}[CorsEndpointProperties] for a complete list of options. [[production-ready-endpoints-custom]] === Implementing Custom Endpoints If you add a `@Bean` annotated with `@Endpoint`, any methods annotated with `@ReadOperation`, `@WriteOperation`, or `@DeleteOperation` are automatically exposed over JMX and, in a web application, over HTTP as well. Endpoints can be exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux. You can also write technology-specific endpoints by using `@JmxEndpoint` or `@WebEndpoint`. These endpoints are restricted to their respective technologies. For example, `@WebEndpoint` is exposed only over HTTP and not over JMX. You can write technology-specific extensions by using `@EndpointWebExtension` and `@EndpointJmxExtension`. These annotations let you provide technology-specific operations to augment an existing endpoint. Finally, if you need access to web-framework-specific functionality, you can implement Servlet or Spring `@Controller` and `@RestController` endpoints at the cost of them not being available over JMX or when using a different web framework. [[production-ready-endpoints-custom-input]] ==== Receiving Input Operations on an endpoint receive input via their parameters. When exposed via the web, the values for these parameters are taken from the URL's query parameters and from the JSON request body. When exposed via JMX, the parameters are mapped to the parameters of the MBean's operations. Parameters are required by default. They can be made optional by annotating them with `@org.springframework.lang.Nullable`. NOTE: To allow the input to be mapped to the operation method's parameters, Java code implementing an endpoint should be compiled with `-parameters`, and Kotlin code implementing an endpoint should be compiled with `-java-parameters`. This will happen automatically if you are using Spring Boot's Gradle plugin or if you are using Maven and `spring-boot-starter-parent`. [[production-ready-endpoints-custom-input-conversion]] ===== Input type conversion The parameters passed to endpoint operation methods are, if necessary, automatically converted to the required type. Before calling an operation method, the input received via JMX or an HTTP request is converted to the required types using an instance of `ApplicationConversionService`. [[production-ready-endpoints-custom-web]] ==== Custom Web Endpoints Operations on an `@Endpoint`, `@WebEndpoint`, or `@EndpointWebExtension` are automatically exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux. [[production-ready-endpoints-custom-web-predicate]] ===== Web Endpoint Request Predicates A request predicate is automatically generated for each operation on a web-exposed endpoint. [[production-ready-endpoints-custom-web-predicate-path]] ===== Path The path of the predicate is determined by the ID of the endpoint and the base path of web-exposed endpoints. The default base path is `/actuator`. For example, an endpoint with the ID `sessions` will use `/actuator/sessions` as its path in the predicate. The path can be further customized by annotating one or more parameters of the operation method with `@Selector`. Such a parameter is added to the path predicate as a path variable. The variable's value is passed into the operation method when the endpoint operation is invoked. [[production-ready-endpoints-custom-web-predicate-http-method]] ===== HTTP method The HTTP method of the predicate is determined by the operation type, as shown in the following table: [cols=""3, 1""] |=== |Operation |HTTP method |`@ReadOperation` |`GET` |`@WriteOperation` |`POST` |`@DeleteOperation` |`DELETE` |=== [[production-ready-endpoints-custom-web-predicate-consumes]] ===== Consumes For a `@WriteOperation` (HTTP `POST`) that uses the request body, the consumes clause of the predicate is `application/vnd.spring-boot.actuator.v2+json, application/json`. For all other operations the consumes clause is empty. [[production-ready-endpoints-custom-web-predicate-produces]] ===== Produces The produces clause of the predicate can be determined by the `produces` attribute of the `@DeleteOperation`, `@ReadOperation`, and `@WriteOperation` annotations. The attribute is optional. If it is not used, the produces clause is determined automatically. If the operation method returns `void` or `Void` the produces clause is empty. If the operation method returns a `org.springframework.core.io.Resource`, the produces clause is `application/octet-stream`. For all other operations the produces clause is `application/vnd.spring-boot.actuator.v2+json, application/json`. [[production-ready-endpoints-custom-web-response-status]] ===== Web Endpoint Response Status The default response status for an endpoint operation depends on the operation type (read, write, or delete) and what, if anything, the operation returns. A `@ReadOperation` returns a value, the response status will be 200 (OK). If it does not return a value, the response status will be 404 (Not Found). If a `@WriteOperation` or `@DeleteOperation` returns a value, the response status will be 200 (OK). If it does not return a value the response status will be 204 (No Content). If an operation is invoked without a required parameter, or with a parameter that cannot be converted to the required type, the operation method will not be called and the response status will be 400 (Bad Request). [[production-ready-endpoints-custom-web-range-requests]] ===== Web Endpoint Range Requests An HTTP range request can be used to request part of an HTTP resource. When using Spring MVC or Spring Web Flux, operations that return a `org.springframework.core.io.Resource` automatically support range requests. NOTE: Range requests are not supported when using Jersey. [[production-ready-endpoints-custom-web-security]] ===== Web Endpoint Security An operation on a web endpoint or a web-specific endpoint extension can receive the current `java.security.Principal` or `org.springframework.boot.actuate.endpoint.SecurityContext` as a method parameter. The former is typically used in conjunction with `@Nullable` to provide different behaviour for authenticated and unauthenticated users. The latter is typically used to perform authorization checks using its `isUserInRole(String)` method. [[production-ready-endpoints-custom-servlet]] ==== Servlet endpoints A `Servlet` can be exposed as an endpoint by implementing a class annotated with `@ServletEndpoint` that also implements `Supplier`. Servlet endpoints provide deeper integration with the Servlet container but at the expense of portability. They are intended to be used to expose an existing `Servlet` as an endpoint. For new endpoints, the `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever possible. [[production-ready-endpoints-custom-controller]] ==== Controller endpoints `@ControllerEndpoint` and `@RestControllerEndpoint` can be used to implement an endpoint that is only exposed by Spring MVC or Spring WebFlux. Methods are mapped using the standard annotations for Spring MVC and Spring WebFlux such as `@RequestMapping` and `@GetMapping`, with the endpoint's ID being used as a prefix for the path. Controller endpoints provide deeper integration with Spring's web frameworks but at the expense of portability. The `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever possible. [[production-ready-health]] === Health Information You can use health information to check the status of your running application. It is often used by monitoring software to alert someone when a production system goes down. The information exposed by the `health` endpoint depends on the `management.endpoint.health.show-details` property which can be configured with one of the following values: [cols=""1, 3""] |=== |Name |Description |`never` |Details are never shown. |`when-authorized` |Details are only shown to authorized users. Authorized roles can be configured using `management.endpoint.health.roles`. |`always` |Details are shown to all users. |=== The default value is `never`. A user is considered to be authorized when they are in one or more of the endpoint's roles. If the endpoint has no configured roles (the default) all authenticated users are considered to be authorized. The roles can be configured using the `management.endpoint.health.roles` property. NOTE: If you have secured your application and wish to use `always`, your security configuration must permit access to the health endpoint for both authenticated and unauthenticated users. Health information is collected from the content of a {sc-spring-boot-actuator}/health/HealthIndicatorRegistry.{sc-ext}[ `HealthIndicatorRegistry`] (by default all {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] instances defined in your `ApplicationContext`. Spring Boot includes a number of auto-configured `HealthIndicators` and you can also write your own. By default, the final system state is derived by the `HealthAggregator` which sorts the statuses from each `HealthIndicator` based on an ordered list of statuses. The first status in the sorted list is used as the overall health status. If no `HealthIndicator` returns a status that is known to the `HealthAggregator`, an `UNKNOWN` status is used. TIP: The `HealthIndicatorRegistry` can be used to register and unregister health indicators at runtime. ==== Auto-configured HealthIndicators The following `HealthIndicators` are auto-configured by Spring Boot when appropriate: [cols=""4,6""] |=== |Name |Description |{sc-spring-boot-actuator}/cassandra/CassandraHealthIndicator.{sc-ext}[`CassandraHealthIndicator`] |Checks that a Cassandra database is up. |{sc-spring-boot-actuator}/system/DiskSpaceHealthIndicator.{sc-ext}[`DiskSpaceHealthIndicator`] |Checks for low disk space. |{sc-spring-boot-actuator}/jdbc/DataSourceHealthIndicator.{sc-ext}[`DataSourceHealthIndicator`] |Checks that a connection to `DataSource` can be obtained. |{sc-spring-boot-actuator}/elasticsearch/ElasticsearchHealthIndicator.{sc-ext}[`ElasticsearchHealthIndicator`] |Checks that an Elasticsearch cluster is up. |{sc-spring-boot-actuator}/influx/InfluxDbHealthIndicator.{sc-ext}[`InfluxDbHealthIndicator`] |Checks that an InfluxDB server is up. |{sc-spring-boot-actuator}/jms/JmsHealthIndicator.{sc-ext}[`JmsHealthIndicator`] |Checks that a JMS broker is up. |{sc-spring-boot-actuator}/mail/MailHealthIndicator.{sc-ext}[`MailHealthIndicator`] |Checks that a mail server is up. |{sc-spring-boot-actuator}/mongo/MongoHealthIndicator.{sc-ext}[`MongoHealthIndicator`] |Checks that a Mongo database is up. |{sc-spring-boot-actuator}/neo4j/Neo4jHealthIndicator.{sc-ext}[`Neo4jHealthIndicator`] |Checks that a Neo4j server is up. |{sc-spring-boot-actuator}/amqp/RabbitHealthIndicator.{sc-ext}[`RabbitHealthIndicator`] |Checks that a Rabbit server is up. |{sc-spring-boot-actuator}/redis/RedisHealthIndicator.{sc-ext}[`RedisHealthIndicator`] |Checks that a Redis server is up. |{sc-spring-boot-actuator}/solr/SolrHealthIndicator.{sc-ext}[`SolrHealthIndicator`] |Checks that a Solr server is up. |=== TIP: You can disable them all by setting the `management.health.defaults.enabled` property. ==== Writing Custom HealthIndicators To provide custom health information, you can register Spring beans that implement the {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] interface. You need to provide an implementation of the `health()` method and return a `Health` response. The `Health` response should include a status and can optionally include additional details to be displayed. The following code shows a sample `HealthIndicator` implementation: [source,java,indent=0] ---- import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class MyHealthIndicator implements HealthIndicator { @Override public Health health() { int errorCode = check(); // perform some specific health check if (errorCode != 0) { return Health.down().withDetail(""Error Code"", errorCode).build(); } return Health.up().build(); } } ---- NOTE: The identifier for a given `HealthIndicator` is the name of the bean without the `HealthIndicator` suffix, if it exists. In the preceding example, the health information is available in an entry named `my`. In addition to Spring Boot's predefined {sc-spring-boot-actuator}/health/Status.{sc-ext}[`Status`] types, it is also possible for `Health` to return a custom `Status` that represents a new system state. In such cases, a custom implementation of the {sc-spring-boot-actuator}/health/HealthAggregator.{sc-ext}[`HealthAggregator`] interface also needs to be provided, or the default implementation has to be configured by using the `management.health.status.order` configuration property. For example, assume a new `Status` with code `FATAL` is being used in one of your `HealthIndicator` implementations. To configure the severity order, add the following property to your application properties: [source,properties,indent=0] ---- management.health.status.order=FATAL, DOWN, OUT_OF_SERVICE, UNKNOWN, UP ---- The HTTP status code in the response reflects the overall health status (for example, `UP` maps to 200, while `OUT_OF_SERVICE` and `DOWN` map to 503). You might also want to register custom status mappings if you access the health endpoint over HTTP. For example, the following property maps `FATAL` to 503 (service unavailable): [source,properties,indent=0] ---- management.health.status.http-mapping.FATAL=503 ---- TIP: If you need more control, you can define your own `HealthStatusHttpMapper` bean. The following table shows the default status mappings for the built-in statuses: [cols=""1,3""] |=== |Status |Mapping |DOWN |SERVICE_UNAVAILABLE (503) |OUT_OF_SERVICE |SERVICE_UNAVAILABLE (503) |UP |No mapping by default, so http status is 200 |UNKNOWN |No mapping by default, so http status is 200 |=== [[reactive-health-indicators]] ==== Reactive Health Indicators For reactive applications, such as those using Spring WebFlux, `ReactiveHealthIndicator` provides a non-blocking contract for getting application health. Similar to a traditional `HealthIndicator`, health information is collected from the content of a {sc-spring-boot-actuator}/health/ReactiveHealthIndicatorRegistry.{sc-ext}[ `ReactiveHealthIndicatorRegistry`] (by default all {sc-spring-boot-actuator}/health/HealthIndicator.{sc-ext}[`HealthIndicator`] and {sc-spring-boot-actuator}/health/ReactiveHealthIndicator.{sc-ext}[ `ReactiveHealthIndicator`] instances defined in your `ApplicationContext`. Regular `HealthIndicator` that do not check against a reactive API are executed on the elastic scheduler. TIP: In a reactive application, The `ReactiveHealthIndicatorRegistry` can be used to register and unregister health indicators at runtime. To provide custom health information from a reactive API, you can register Spring beans that implement the {sc-spring-boot-actuator}/health/ReactiveHealthIndicator.{sc-ext}[`ReactiveHealthIndicator`] interface. The following code shows a sample `ReactiveHealthIndicator` implementation: [source,java,indent=0] ---- @Component public class MyReactiveHealthIndicator implements ReactiveHealthIndicator { @Override public Mono health() { return doHealthCheck() //perform some specific health check that returns a Mono .onErrorResume(ex -> Mono.just(new Health.Builder().down(ex).build()))); } } ---- TIP: To handle the error automatically, consider extending from `AbstractReactiveHealthIndicator`. ==== Auto-configured ReactiveHealthIndicators The following `ReactiveHealthIndicators` are auto-configured by Spring Boot when appropriate: [cols=""1,4""] |=== |Name |Description |{sc-spring-boot-actuator}/cassandra/CassandraReactiveHealthIndicator.{sc-ext}[`CassandraReactiveHealthIndicator`] |Checks that a Cassandra database is up. |{sc-spring-boot-actuator}/mongo/MongoReactiveHealthIndicator.{sc-ext}[`MongoReactiveHealthIndicator`] |Checks that a Mongo database is up. |{sc-spring-boot-actuator}/redis/RedisReactiveHealthIndicator.{sc-ext}[`RedisReactiveHealthIndicator`] |Checks that a Redis server is up. |=== TIP: If necessary, reactive indicators replace the regular ones. Also, any `HealthIndicator` that is not handled explicitly is wrapped automatically. [[production-ready-application-info]] === Application Information Application information exposes various information collected from all {sc-spring-boot-actuator}/info/InfoContributor.{sc-ext}[`InfoContributor`] beans defined in your `ApplicationContext`. Spring Boot includes a number of auto-configured `InfoContributor` beans, and you can write your own. [[production-ready-application-info-autoconfigure]] ==== Auto-configured InfoContributors The following `InfoContributor` beans are auto-configured by Spring Boot, when appropriate: [cols=""1,4""] |=== |Name |Description |{sc-spring-boot-actuator}/info/EnvironmentInfoContributor.{sc-ext}[`EnvironmentInfoContributor`] |Exposes any key from the `Environment` under the `info` key. |{sc-spring-boot-actuator}/info/GitInfoContributor.{sc-ext}[`GitInfoContributor`] |Exposes git information if a `git.properties` file is available. |{sc-spring-boot-actuator}/info/BuildInfoContributor.{sc-ext}[`BuildInfoContributor`] |Exposes build information if a `META-INF/build-info.properties` file is available. |=== TIP: It is possible to disable them all by setting the `management.info.defaults.enabled` property. [[production-ready-application-info-env]] ==== Custom Application Information You can customize the data exposed by the `info` endpoint by setting `+info.*+` Spring properties. All `Environment` properties under the `info` key are automatically exposed. For example, you could add the following settings to your `application.properties` file: [source,properties,indent=0] ---- info.app.encoding=UTF-8 info.app.java.source=1.8 info.app.java.target=1.8 ---- [TIP] ==== Rather than hardcoding those values, you could also <>. Assuming you use Maven, you could rewrite the preceding example as follows: [source,properties,indent=0] ---- info.app.encoding=@project.build.sourceEncoding@ info.app.java.source=@java.version@ info.app.java.target=@java.version@ ---- ==== [[production-ready-application-info-git]] ==== Git Commit Information Another useful feature of the `info` endpoint is its ability to publish information about the state of your `git` source code repository when the project was built. If a `GitProperties` bean is available, the `git.branch`, `git.commit.id`, and `git.commit.time` properties are exposed. TIP: A `GitProperties` bean is auto-configured if a `git.properties` file is available at the root of the classpath. See ""<>"" for more details. If you want to display the full git information (that is, the full content of `git.properties`), use the `management.info.git.mode` property, as follows: [source,properties,indent=0] ---- management.info.git.mode=full ---- [[production-ready-application-info-build]] ==== Build Information If a `BuildProperties` bean is available, the `info` endpoint can also publish information about your build. This happens if a `META-INF/build-info.properties` file is available in the classpath. TIP: The Maven and Gradle plugins can both generate that file. See ""<>"" for more details. [[production-ready-application-info-custom]] ==== Writing Custom InfoContributors To provide custom application information, you can register Spring beans that implement the {sc-spring-boot-actuator}/info/InfoContributor.{sc-ext}[`InfoContributor`] interface. The following example contributes an `example` entry with a single value: [source,java,indent=0] ---- import java.util.Collections; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class ExampleInfoContributor implements InfoContributor { @Override public void contribute(Info.Builder builder) { builder.withDetail(""example"", Collections.singletonMap(""key"", ""value"")); } } ---- If you reach the `info` endpoint, you should see a response that contains the following additional entry: [source,json,indent=0] ---- { ""example"": { ""key"" : ""value"" } } ---- [[production-ready-monitoring]] == Monitoring and Management over HTTP If you are developing a web application, Spring Boot Actuator auto-configures all enabled endpoints to be exposed over HTTP. The default convention is to use the `id` of the endpoint with a prefix of `/actuator` as the URL path. For example, `health` is exposed as `/actuator/health`. TIP: Actuator is supported natively with Spring MVC, Spring WebFlux, and Jersey. [[production-ready-customizing-management-server-context-path]] === Customizing the Management Endpoint Paths Sometimes, it is useful to customize the prefix for the management endpoints. For example, your application might already use `/actuator` for another purpose. You can use the `management.endpoints.web.base-path` property to change the prefix for your management endpoint, as shown in the following example: [source,properties,indent=0] ---- management.endpoints.web.base-path=/manage ---- The preceding `application.properties` example changes the endpoint from `/actuator/{id}` to `/manage/{id}` (for example, `/manage/info`). NOTE: Unless the management port has been configured to <>, `management.endpoints.web.base-path` is relative to `server.servlet.context-path`. If `management.server.port` is configured, `management.endpoints.web.base-path` is relative to `management.server.servlet.context-path`. [[production-ready-customizing-management-server-port]] === Customizing the Management Server Port Exposing management endpoints by using the default HTTP port is a sensible choice for cloud-based deployments. If, however, your application runs inside your own data center, you may prefer to expose endpoints by using a different HTTP port. You can set the `management.server.port` property to change the HTTP port, as shown in the following example: [source,properties,indent=0] ---- management.server.port=8081 ---- [[production-ready-management-specific-ssl]] === Configuring Management-specific SSL When configured to use a custom port, the management server can also be configured with its own SSL by using the various `management.server.ssl.*` properties. For example, doing so lets a management server be available over HTTP while the main application uses HTTPS, as shown in the following property settings: [source,properties,indent=0] ---- server.port=8443 server.ssl.enabled=true server.ssl.key-store=classpath:store.jks server.ssl.key-password=secret management.server.port=8080 management.server.ssl.enabled=false ---- Alternatively, both the main server and the management server can use SSL but with different key stores, as follows: [source,properties,indent=0] ---- server.port=8443 server.ssl.enabled=true server.ssl.key-store=classpath:main.jks server.ssl.key-password=secret management.server.port=8080 management.server.ssl.enabled=true management.server.ssl.key-store=classpath:management.jks management.server.ssl.key-password=secret ---- [[production-ready-customizing-management-server-address]] === Customizing the Management Server Address You can customize the address that the management endpoints are available on by setting the `management.server.address` property. Doing so can be useful if you want to listen only on an internal or ops-facing network or to listen only for connections from `localhost`. NOTE: You can listen on a different address only when the port differs from the main server port. The following example `application.properties` does not allow remote management connections: [source,properties,indent=0] ---- management.server.port=8081 management.server.address=127.0.0.1 ---- [[production-ready-disabling-http-endpoints]] === Disabling HTTP Endpoints If you do not want to expose endpoints over HTTP, you can set the management port to `-1`, as shown in the following example: [source,properties,indent=0] ---- management.server.port=-1 ---- [[production-ready-jmx]] == Monitoring and Management over JMX Java Management Extensions (JMX) provide a standard mechanism to monitor and manage applications. By default, Spring Boot exposes management endpoints as JMX MBeans under the `org.springframework.boot` domain. [[production-ready-custom-mbean-names]] === Customizing MBean Names The name of the MBean is usually generated from the `id` of the endpoint. For example, the `health` endpoint is exposed as `org.springframework.boot:type=Endpoint,name=Health`. If your application contains more than one Spring `ApplicationContext`, you may find that names clash. To solve this problem, you can set the `spring.jmx.unique-names` property to `true` so that MBean names are always unique. You can also customize the JMX domain under which endpoints are exposed. The following settings show an example of doing so in `application.properties`: [source,properties,indent=0] ---- spring.jmx.unique-names=true management.endpoints.jmx.domain=com.example.myapp ---- [[production-ready-disable-jmx-endpoints]] === Disabling JMX Endpoints If you do not want to expose endpoints over JMX, you can set the `management.endpoints.jmx.exposure.exclude` property to `*`, as shown in the following example: [source,properties,indent=0] ---- management.endpoints.jmx.exposure.exclude=* ---- [[production-ready-jolokia]] === Using Jolokia for JMX over HTTP Jolokia is a JMX-HTTP bridge that provides an alternative method of accessing JMX beans. To use Jolokia, include a dependency to `org.jolokia:jolokia-core`. For example, with Maven, you would add the following dependency: [source,xml,indent=0] ---- org.jolokia jolokia-core ---- The Jolokia endpoint can then be exposed by adding `jolokia` or `*` to the `management.endpoints.web.exposure.include` property. You can then access it by using `/actuator/jolokia` on your management HTTP server. [[production-ready-customizing-jolokia]] ==== Customizing Jolokia Jolokia has a number of settings that you would traditionally configure by setting servlet parameters. With Spring Boot, you can use your `application.properties` file. To do so, prefix the parameter with `management.endpoint.jolokia.config.`, as shown in the following example: [source,properties,indent=0] ---- management.endpoint.jolokia.config.debug=true ---- [[production-ready-disabling-jolokia]] ==== Disabling Jolokia If you use Jolokia but do not want Spring Boot to configure it, set the `management.endpoint.jolokia.enabled` property to `false`, as follows: [source,properties,indent=0] ---- management.endpoint.jolokia.enabled=false ---- [[production-ready-loggers]] == Loggers Spring Boot Actuator includes the ability to view and configure the log levels of your application at runtime. You can view either the entire list or an individual logger's configuration, which is made up of both the explicitly configured logging level as well as the effective logging level given to it by the logging framework. These levels can be one of: * `TRACE` * `DEBUG` * `INFO` * `WARN` * `ERROR` * `FATAL` * `OFF` * `null` `null` indicates that there is no explicit configuration. [[production-ready-logger-configuration]] === Configure a Logger To configure a given logger, `POST` a partial entity to the resource's URI, as shown in the following example: [source,json,indent=0] ---- { ""configuredLevel"": ""DEBUG"" } ---- TIP: To ""`reset`"" the specific level of the logger (and use the default configuration instead), you can pass a value of `null` as the `configuredLevel`. [[production-ready-metrics]] == Metrics Spring Boot Actuator provides dependency management and auto-configuration for https://micrometer.io[Micrometer], an application metrics facade that supports numerous monitoring systems, including: - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> TIP: To learn more about Micrometer's capabilities, please refer to its https://micrometer.io/docs[reference documentation], in particular the {micrometer-concepts-documentation}[concepts section]. [[production-ready-metrics-getting-started]] === Getting started Spring Boot auto-configures a composite `MeterRegistry` and adds a registry to the composite for each of the supported implementations that it finds on the classpath. Having a dependency on `micrometer-registry-{system}` in your runtime classpath is enough for Spring Boot to configure the registry. Most registries share common features. For instance, you can disable a particular registry even if the Micrometer registry implementation is on the classpath. For instance, to disable Datadog: [source,properties,indent=0] ---- management.metrics.export.datadog.enabled=false ---- Spring Boot will also add any auto-configured registries to the global static composite registry on the `Metrics` class unless you explicitly tell it not to: [source,properties,indent=0] ---- management.metrics.use-global-registry=false ---- You can register any number of `MeterRegistryCustomizer` beans to further configure the registry, such as applying common tags, before any meters are registered with the registry: [source,java,indent=0] ---- @Bean MeterRegistryCustomizer metricsCommonTags() { return registry -> registry.config().commonTags(""region"", ""us-east-1""); } ---- You can apply customizations to particular registry implementations by being more specific about the generic type: [source,java,indent=0] ---- @Bean MeterRegistryCustomizer graphiteMetricsNamingConvention() { return registry -> registry.config().namingConvention(MY_CUSTOM_CONVENTION); } ---- With that setup in place you can inject `MeterRegistry` in your components and register metrics: [source,java,indent=0] ---- include::{code-examples}/actuate/metrics/SampleBean.java[tag=example] ---- Spring Boot also <> (i.e. `MeterBinder` implementations) that you can control via configuration or dedicated annotation markers. [[production-ready-metrics-export]] === Supported monitoring systems [[production-ready-metrics-export-atlas]] ==== Atlas By default, metrics are exported to {micrometer-registry-documentation}/atlas[Atlas] running on your local machine. The location of the https://github.com/Netflix/atlas[Atlas server] to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.atlas.uri=http://atlas.example.com:7101/api/v1/publish ---- [[production-ready-metrics-export-datadog]] ==== Datadog Datadog registry pushes metrics to https://www.datadoghq.com[datadoghq] periodically. To export metrics to {micrometer-registry-documentation}/datadog[Datadog], your API key must be provided: [source,properties,indent=0] ---- management.metrics.export.datadog.api-key=YOUR_KEY ---- You can also change the interval at which metrics are sent to Datadog: [source,properties,indent=0] ---- management.metrics.export.datadog.step=30s ---- [[production-ready-metrics-export-ganglia]] ==== Ganglia By default, metrics are exported to {micrometer-registry-documentation}/ganglia[Ganglia] running on your local machine. The http://ganglia.sourceforge.net[Ganglia server] host and port to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.ganglia.host=ganglia.example.com management.metrics.export.ganglia.port=9649 ---- [[production-ready-metrics-export-graphite]] ==== Graphite By default, metrics are exported to {micrometer-registry-documentation}/graphite[Graphite] running on your local machine. The https://graphiteapp.org[Graphite server] host and port to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.graphite.host=graphite.example.com management.metrics.export.graphite.port=9004 ---- Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter id is {micrometer-registry-documentation}/graphite#_hierarchical_name_mapping[mapped to flat hierarchical names]. TIP: To take control over this behaviour, define your `GraphiteMeterRegistry` and supply your own `HierarchicalNameMapper`. An auto-configured `GraphiteConfig` and `Clock` beans are provided unless you define your own: [source,java] ---- @Bean public GraphiteMeterRegistry graphiteMeterRegistry(GraphiteConfig config, Clock clock) { return new GraphiteMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER); } ---- [[production-ready-metrics-export-influx]] ==== Influx By default, metrics are exported to {micrometer-registry-documentation}/influx[Influx] running on your local machine. The location of the https://www.influxdata.com[Influx server] to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.influx.uri=http://influx.example.com:8086 ---- [[production-ready-metrics-export-jmx]] ==== JMX Micrometer provides a hierarchical mapping to {micrometer-registry-documentation}/jmx[JMX], primarily as a cheap and portable way to view metrics locally.By default, metrics are exported to the `metrics` JMX domain. The domain to use can be provided provided using: [source,properties,indent=0] ---- management.metrics.export.jmx.domain=com.example.app.metrics ---- Micrometer provides a default `HierarchicalNameMapper` that governs how a dimensional meter id is {micrometer-registry-documentation}/jmx#_hierarchical_name_mapping[mapped to flat hierarchical names]. TIP: To take control over this behaviour, define your `JmxMeterRegistry` and supply your own `HierarchicalNameMapper`. An auto-configured `JmxConfig` and `Clock` beans are provided unless you define your own: [source,java] ---- @Bean public JmxMeterRegistry jmxMeterRegistry(JmxConfig config, Clock clock) { return new JmxMeterRegistry(config, clock, MY_HIERARCHICAL_MAPPER); } ---- [[production-ready-metrics-export-newrelic]] ==== New Relic New Relic registry pushes metrics to {micrometer-registry-documentation}/new-relic[New Relic] periodically. To export metrics to https://newrelic.com[New Relic], your API key and account id must be provided: [source,properties,indent=0] ---- management.metrics.export.newrelic.api-key=YOUR_KEY management.metrics.export.newrelic.account-id=YOUR_ACCOUNT_ID ---- You can also change the interval at which metrics are sent to New Relic: [source,properties,indent=0] ---- management.metrics.export.newrelic.step=30s ---- [[production-ready-metrics-export-prometheus]] ==== Prometheus {micrometer-registry-documentation}/prometheus[Prometheus] expects to scrape or poll individual app instances for metrics. Spring Boot provides an actuator endpoint available at `/actuator/prometheus` to present a https://prometheus.io[Prometheus scrape] with the appropriate format. TIP: The endpoint is not available by default and must be exposed, see <> for more details. Here is an example `scrape_config` to add to `prometheus.yml`: [source,yaml,indent=0] ---- scrape_configs: - job_name: 'spring' metrics_path: '/actuator/prometheus' static_configs: - targets: ['HOST:PORT'] ---- [[production-ready-metrics-export-signalfx]] ==== SignalFx SignalFx registry pushes metrics to {micrometer-registry-documentation}/signalfx[SignalFx] periodically. To export metrics to https://signalfx.com[SignalFx], your access token must be provided: [source,properties,indent=0] ---- management.metrics.export.signalfx.access-token=YOUR_ACCESS_TOKEN ---- You can also change the interval at which metrics are sent to SignalFx: [source,properties,indent=0] ---- management.metrics.export.signalfx.step=30s ---- [[production-ready-metrics-export-simple]] ==== Simple Micrometer ships with a simple, in-memory backend that is automatically used as a fallback if no other registry is configured. This allows you to see what metrics are collected in the <>. The in-memory backend disables itself as soon as you're using any of the other available backend. You can also disable it explicitly: [source,properties,indent=0] ---- management.metrics.export.simple.enabled=false ---- [[production-ready-metrics-export-statsd]] ==== StatsD The StatsD registry pushes metrics over UDP to a StatsD agent eagerly. By default, metrics are exported to a {micrometer-registry-documentation}/statsd[StatsD] agent running on your local machine. The StatsD agent host and port to use can be provided using: [source,properties,indent=0] ---- management.metrics.export.statsd.host=statsd.example.com management.metrics.export.statsd.port=9125 ---- You can also change the StatsD line protocol to use (default to Datadog): [source,properties,indent=0] ---- management.metrics.export.statsd.flavor=etsy ---- [[production-ready-metrics-export-wavefront]] ==== Wavefront Wavefront registry pushes metrics to {micrometer-registry-documentation}/wavefront[Wavefront] periodically. If you are exporting metrics to https://www.wavefront.com/[Wavefront] directly, your API token must be provided: [source,properties,indent=0] ---- management.metrics.export.wavefront.api-token=YOUR_API_TOKEN ---- Alternatively, you may use a Wavefront sidecar or an internal proxy set up in your environment that forwards metrics data to the Wavefront API host: [source,properties,indent=0] ---- management.metrics.export.wavefront.uri=proxy://localhost:2878 ---- TIP: If publishing metrics to a Wavefront proxy (as described in https://docs.wavefront.com/proxies_installing.html[the documentation]), the host must be in the `proxy://HOST:PORT` format. You can also change the interval at which metrics are sent to Wavefront: [source,properties,indent=0] ---- management.metrics.export.wavefront.step=30s ---- [[production-ready-metrics-meter]] === Supported Metrics Spring Boot registers the following core metrics when applicable: * JVM metrics, report utilization of: ** Various memory and buffer pools ** Statistics related to garbage collection ** Threads utilization ** Number of classes loaded/unloaded * CPU metrics * File descriptor metrics * Logback metrics: record the number of events logged to Logback at each level * Uptime metrics: report a gauge for uptime and a fixed gauge representing the application's absolute start time * Tomcat metrics * https://docs.spring.io/spring-integration/docs/current/reference/html/system-management-chapter.html#micrometer-integration[Spring Integration] metrics [[production-ready-metrics-spring-mvc]] ==== Spring MVC Metrics Auto-configuration enables the instrumentation of requests handled by Spring MVC. When `management.metrics.web.server.auto-time-requests` is `true`, this instrumentation occurs for all requests. Alternatively, when set to `false`, you can enable instrumentation by adding `@Timed` to a request-handling method: [source,java,indent=0] ---- @RestController @Timed <1> public class MyController { @GetMapping(""/api/people"") @Timed(extraTags = { ""region"", ""us-east-1"" }) <2> @Timed(value = ""all.people"", longTask = true) <3> public List listPeople() { ... } } ---- <1> A controller class to enable timings on every request handler in the controller. <2> A method to enable for an individual endpoint. This is not necessary if you have it on the class, but can be used to further customize the timer for this particular endpoint. <3> A method with `longTask = true` to enable a long task timer for the method. Long task timers require a separate metric name, and can be stacked with a short task timer. By default, metrics are generated with the name, `http.server.requests`. The name can be customized by setting the `management.metrics.web.server.requests-metric-name` property. By default, Spring MVC-related metrics are tagged with the following information: * `method`, the request's method (for example, `GET` or `POST`). * `uri`, the request's URI template prior to variable substitution, if possible (for example, `/api/person/{id}`). * `status`, the response's HTTP status code (for example, `200` or `500`). * `exception`, the simple class name of any exception that was thrown while handling the request. To customize the tags, provide a `@Bean` that implements `WebMvcTagsProvider`. [[production-ready-metrics-web-flux]] ==== Spring WebFlux Metrics Auto-configuration enables the instrumentation of all requests handled by WebFlux controllers and functional handlers. By default, metrics are generated with the name `http.server.requests`. You can customize the name by setting the `management.metrics.web.server.requests-metric-name` property. By default, WebFlux-related metrics are tagged with the following information: * `method`, the request's method (for example, `GET` or `POST`). * `uri`, the request's URI template prior to variable substitution, if possible (for example, `/api/person/{id}`). * `status`, the response's HTTP status code (for example, `200` or `500`). * `exception`, the simple class name of any exception that was thrown while handling the request. To customize the tags, provide a `@Bean` that implements `WebFluxTagsProvider`. [[production-ready-metrics-http-clients]] ==== HTTP Client Metrics Spring Boot Actuator manages the instrumentation of both `RestTemplate` and `WebClient`. For that, you have to get injected with an auto-configured builder and use it to create instances: * `RestTemplateBuilder` for `RestTemplate` * `WebClient.Builder` for `WebClient` It is also possible to apply manually the customizers responsible for this instrumentation, namely `MetricsRestTemplateCustomizer` and `MetricsWebClientCustomizer`. By default, metrics are generated with the name, `http.client.requests`. The name can be customized by setting the `management.metrics.web.client.requests-metric-name` property. By default, metrics generated by an instrumented client are tagged with the following information: * `method`, the request's method (for example, `GET` or `POST`). * `uri`, the request's URI template prior to variable substitution, if possible (for example, `/api/person/{id}`). * `status`, the response's HTTP status code (for example, `200` or `500`). * `clientName`, the host portion of the URI. To customize the tags, and depending on your choice of client, you can provide a `@Bean` that implements `RestTemplateExchangeTagsProvider` or `WebClientExchangeTagsProvider`. There are convenience static functions in `RestTemplateExchangeTags` and `WebClientExchangeTags`. [[production-ready-metrics-cache]] ==== Cache Metrics Auto-configuration enables the instrumentation of all available ``Cache``s on startup with metrics prefixed with `cache`. Cache instrumentation is standardized for a basic set of metrics. Additional, cache-specific metrics are also available. The following cache libraries are supported: * Caffeine * EhCache 2 * Hazelcast * Any compliant JCache (JSR-107) implementation Metrics are tagged by the name of the cache and by the name of the `CacheManager` that is derived from the bean name. NOTE: Only caches that are available on startup are bound to the registry. For caches created on-the-fly or programmatically after the startup phase, an explicit registration is required. A `CacheMetricsRegistrar` bean is made available to make that process easier. [[production-ready-metrics-jdbc]] ==== DataSource Metrics Auto-configuration enables the instrumentation of all available `DataSource` objects with a metric named `jdbc`. Data source instrumentation results in gauges representing the currently active, maximum allowed, and minimum allowed connections in the pool. Each of these gauges has a name that is prefixed by `jdbc`. Metrics are also tagged by the name of the `DataSource` computed based on the bean name. TIP: By default, Spring Boot provides metadata for all supported data sources; you can add additional `DataSourcePoolMetadataProvider` beans if your favorite data source isn't supported out of the box. See `DataSourcePoolMetadataProvidersConfiguration` for examples. Also, Hikari-specific metrics are exposed with a `hikaricp` prefix. Each metric is tagged by the name of the Pool (can be controlled with `spring.datasource.name`). [[production-ready-metrics-hibernate]] ==== Hibernate Metrics Auto-configuration enables the instrumentation of all available Hibernate `EntityManagerFactory` instances that have statistics enabled with a metric named `hibernate`. Metrics are also tagged by the name of the `EntityManagerFactory` that is derived from the bean name. To enable statistics, the standard JPA property `hibernate.generate_statistics` must be set to `true`. You can enable that on the auto-configured `EntityManagerFactory` as shown in the following example: [source,properties,indent=0] ---- spring.jpa.properties.hibernate.generate_statistics=true ---- [[production-ready-metrics-rabbitmq]] ==== RabbitMQ Metrics Auto-configuration will enable the instrumentation of all available RabbitMQ connection factories with a metric named `rabbitmq`. [[production-ready-metrics-custom]] === Registering custom metrics To register custom metrics, inject `MeterRegistry` into your component, as shown in the following example: [source,java,indent=0] ---- include::{code-examples}/actuate/metrics/MetricsMeterRegistryInjectionExample.java[tag=component] ---- If you find that you repeatedly instrument a suite of metrics across components or applications, you may encapsulate this suite in a `MeterBinder` implementation. By default, metrics from all `MeterBinder` beans will be automatically bound to the Spring-managed `MeterRegistry`. [[production-ready-metrics-per-meter-properties]] === Customizing individual metrics If you need to apply customizations to specific `Meter` instances you can use the `io.micrometer.core.instrument.config.MeterFilter` interface. By default, all `MeterFilter` beans will be automatically applied to the micrometer `MeterRegistry.Config`. For example, if you want to rename the `mytag.region` tag to `mytag.area` for all meter IDs beginning with `com.example`, you can do the following: [source,java,indent=0] ---- include::{code-examples}/actuate/metrics/MetricsFilterBeanExample.java[tag=configuration] ---- [[production-ready-metrics-common-tags]] ==== Common tags Common tags are generally used for dimensional drill-down on the operating environment like host, instance, region, stack, etc. Commons tags are applied to all meters and can be configured as shown in the following example: [source,properties,indent=0] ---- management.metrics.tags.region=us-east-1 management.metrics.tags.stack=prod ---- The example above adds `region` and `stack` tags to all meters with a value of `us-east-1` and `prod` respectively. NOTE: The order of common tags is important if you are using Graphite. As the order of common tags cannot be guaranteed using this approach, Graphite users are advised to define a custom `MeterFilter` instead. ==== Per-meter properties In addition to `MeterFilter` beans, it's also possible to apply a limited set of customization on a per-meter basis using properties. Per-meter customizations apply to any all meter IDs that start with the given name. For example, the following will disable any meters that have an ID starting with `example.remote` [source,properties,indent=0] ---- management.metrics.enable.example.remote=false ---- The following properties allow per-meter customization: .Per-meter customizations |=== | Property | Description | `management.metrics.enable` | Whether to deny meters from emitting any metrics. | `management.metrics.distribution.percentiles-histogram` | Whether to publish a histogram suitable for computing aggregable (across dimension) percentile approximations. | `management.metrics.distribution.percentiles` | Publish percentile values computed in your application | `management.metrics.distribution.sla` | Publish a cumulative histogram with buckets defined by your SLAs. |=== For more details on concepts behind `percentiles-histogram`, `percentiles` and `sla` refer to the {micrometer-concepts-documentation}#_histograms_and_percentiles[""Histograms and percentiles"" section] of the micrometer documentation. [[production-ready-metrics-endpoint]] === Metrics endpoint Spring Boot provides a `metrics` endpoint that can be used diagnostically to examine the metrics collected by an application. The endpoint is not available by default and must be exposed, see <> for more details. Navigating to `/actuator/metrics` displays a list of available meter names. You can drill down to view information about a particular meter by providing its name as a selector, e.g. `/actuator/metrics/jvm.memory.max`. [TIP] ==== The name you use here should match the name used in the code, not the name after it has been naming-convention normalized for a monitoring system it is shipped to. In other words, if `jvm.memory.max` appears as `jvm_memory_max` in Prometheus because of its snake case naming convention, you should still use `jvm.memory.max` as the selector when inspecting the meter in the `metrics` endpoint. ==== You can also add any number of `tag=KEY:VALUE` query parameters to the end of the URL to dimensionally drill down on a meter, e.g. `/actuator/metrics/jvm.memory.max?tag=area:nonheap`. [TIP] ==== The reported measurements are the _sum_ of the statistics of all meters matching the meter name and any tags that have been applied. So in the example above, the returned ""Value"" statistic is the sum of the maximum memory footprints of ""Code Cache"", ""Compressed Class Space"", and ""Metaspace"" areas of the heap. If you just wanted to see the maximum size for the ""Metaspace"", you could add an additional `tag=id:Metaspace`, i.e. `/actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace`. ==== [[production-ready-auditing]] == Auditing Once Spring Security is in play, Spring Boot Actuator has a flexible audit framework that publishes events (by default, ""`authentication success`"", ""`failure`"" and ""`access denied`"" exceptions). This feature can be very useful for reporting and for implementing a lock-out policy based on authentication failures. To customize published security events, you can provide your own implementations of `AbstractAuthenticationAuditListener` and `AbstractAuthorizationAuditListener`. You can also use the audit services for your own business events. To do so, either inject the existing `AuditEventRepository` into your own components and use that directly or publish an `AuditApplicationEvent` with the Spring `ApplicationEventPublisher` (by implementing `ApplicationEventPublisherAware`). [[production-ready-http-tracing]] == HTTP Tracing Tracing is automatically enabled for all HTTP requests. You can view the `httptrace` endpoint and obtain basic information about the last 100 request-response exchanges. [[production-ready-http-tracing-custom]] === Custom HTTP tracing To customize the items that are included in each trace, use the `management.trace.http.include` configuration property. For advanced customization, consider registering your own `HttpExchangeTracer` implementation. By default, an `InMemoryHttpTraceRepository` that stores traces for the last 100 request-response exchanges is used. If you need to expand the capacity, you can define your own instance of the `InMemoryHttpTraceRepository` bean. You can also create your own alternative `HttpTraceRepository` implementation. [[production-ready-process-monitoring]] == Process Monitoring In the `spring-boot` module, you can find two classes to create files that are often useful for process monitoring: * `ApplicationPidFileWriter` creates a file containing the application PID (by default, in the application directory with a file name of `application.pid`). * `WebServerPortFileWriter` creates a file (or files) containing the ports of the running web server (by default, in the application directory with a file name of `application.port`). By default, these writers are not activated, but you can enable: * <> * <> [[production-ready-process-monitoring-configuration]] === Extending Configuration In the `META-INF/spring.factories` file, you can activate the listener(s) that writes a PID file, as shown in the following example: [indent=0] ---- org.springframework.context.ApplicationListener=\\ org.springframework.boot.context.ApplicationPidFileWriter,\\ org.springframework.boot.web.context.WebServerPortFileWriter ---- [[production-ready-process-monitoring-programmatically]] === Programmatically You can also activate a listener by invoking the `SpringApplication.addListeners(...)` method and passing the appropriate `Writer` object. This method also lets you customize the file name and path in the `Writer` constructor. [[production-ready-cloudfoundry]] == Cloud Foundry Support Spring Boot's actuator module includes additional support that is activated when you deploy to a compatible Cloud Foundry instance. The `/cloudfoundryapplication` path provides an alternative secured route to all `@Endpoint` beans. The extended support lets Cloud Foundry management UIs (such as the web application that you can use to view deployed applications) be augmented with Spring Boot actuator information. For example, an application status page may include full health information instead of the typical ""`running`"" or ""`stopped`"" status. NOTE: The `/cloudfoundryapplication` path is not directly accessible to regular users. In order to use the endpoint, a valid UAA token must be passed with the request. [[production-ready-cloudfoundry-disable]] === Disabling Extended Cloud Foundry Actuator Support If you want to fully disable the `/cloudfoundryapplication` endpoints, you can add the following setting to your `application.properties` file: .application.properties [source,properties,indent=0] ---- management.cloudfoundry.enabled=false ---- [[production-ready-cloudfoundry-ssl]] === Cloud Foundry Self-signed Certificates By default, the security verification for `/cloudfoundryapplication` endpoints makes SSL calls to various Cloud Foundry services. If your Cloud Foundry UAA or Cloud Controller services use self-signed certificates, you need to set the following property: .application.properties [source,properties,indent=0] ---- management.cloudfoundry.skip-ssl-validation=true ---- === Custom context path If the server's context-path has been configured to anything other than `/`, the Cloud Foundry endpoints will not be available at the root of the application. For example, if `server.servlet.context-path=/app`, Cloud Foundry endpoints will be available at `/app/cloudfoundryapplication/*`. If you expect the Cloud Foundry endpoints to always be available at `/cloudfoundryapplication/*`, regardless of the server's context-path, you will need to explicitly configure that in your application. The configuration will differ depending on the web server in use. For Tomcat, the following configuration can be added: [source,java,indent=0] ---- include::{code-examples}/cloudfoundry/CloudFoundryCustomContextPathExample.java[tag=configuration] ---- [[production-ready-whats-next]] == What to Read Next If you want to explore some of the concepts discussed in this chapter, you can take a look at the actuator {github-code}/spring-boot-samples[sample applications]. You also might want to read about graphing tools such as http://graphite.wikidot.com/[Graphite]. Otherwise, you can continue on, to read about <> or jump ahead for some in-depth information about Spring Boot's _<>_. ",16143,True,2843.3206809588064,median "//// Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. //// anchor:gremlin-variants[] [[gremlin-drivers-variants]] = Gremlin Drivers and Variants image::gremlin-house-of-mirrors.png[width=1024] At this point, readers should be well familiar with the <> to this Reference Documentation and will likely be thinking about implementation details specific to the graph provider they have selected as well as the programming language they intend to use. The choice of programming language could have implications to the architecture and design of the application and the choice itself may have limits imposed upon it by the chosen graph provider. For example, a <> will require the selection of a driver to interact with it. On the other hand, a graph system that is designed for embedded use, like TinkerGraph, needs the Java Virtual Machine (JVM) environment so will require <>, if using a programming language that is not on the JVM and will further require driver selection. TinkerPop provides an array of drivers in different programming languages as a way to connect to a remote Gremlin Server or Remote Gremlin Provider. Drivers allow the developer to make requests to that remote system and get back results from the TinkerPop-enabled graphs hosted within. A driver can submit Gremlin strings and Gremlin bytecode over this sub-protocol. Gremlin strings are written in the scripting language made available by the remote system that the driver is connecting to (typically, Groovy-based). This connection approach is quite similar to what developers are likely familiar with when using JDBC and SQL. While it is familiar, it is not recommended and for TinkerPop it is considered an out-dated concept and is largely still present for the purpose of supporting applications that might still be using that method of interaction. The preferred approach is to use bytecode-based requests, which essentially allows the ability to craft Gremlin directly in the programming language of choice. As Gremlin makes use of two fundamental programming constructs: link:https://en.wikipedia.org/wiki/Function_composition[function composition] and link:https://en.wikipedia.org/wiki/Nested_function[function nesting]. it is possible to embed the Gremlin language in any modern programming language. It is a far more natural way to program, because it enables IDE interaction, compile time checks, and language level checks that can help prevent errors prior to execution. The differences between these two approaches were outlined in the <> Section, which applies to Gremlin Server, but also to Remote Gremlin Providers. In addition to the languages and drivers that TinkerPop supports, there are also third-party implementations, as well as extensions to the Gremlin language that might be specific to a particular graph provider. That listing can be found on the TinkerPop link:https://tinkerpop.apache.org/#graph-systems[home page]. Their description is beyond the scope of this documentation. TIP: When possible, it is typically best to align the version of TinkerPop used on the client with the version supported on the server. While it is not impossible to have a different version between client and server, it may require additional configuration and/or a deeper knowledge of that changes introduced between versions. It's simply safer to avoid the conflict, when allowed to do so. IMPORTANT: Gremlin-Java is the canonical representation of Gremlin and any (proper) Gremlin language variant will emulate its structure as best as possible given the constructs of the host language. A strong correspondence between variants ensures that the general Gremlin reference documentation is applicable to all variants and that users moving between development languages can easily adopt the Gremlin variant for that language. image::gremlin-variant-architecture.png[width=650,float=left] NOTE: The information herein describes how to use the Gremlin language variants distributed with Apache TinkerPop. For information on how to build a Gremlin language variant, please review the link:https://tinkerpop.apache.org/docs/x.y.z/tutorials/gremlin-language-variants/[Gremlin Language Variants] tutorial. The following sections describe each language variant and driver that is officially TinkerPop a part of the project, provided more detailed information about usage, configuration and known limitations. anchor:connecting-via-remotegraph[] anchor:connecting-via-java[] [[gremlin-java]] == Gremlin-Java image:gremlin-java-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Java implements Gremlin within the Java language and can be used by any Java Virtual Machine. Gremlin-Java is considered the canonical, reference implementation of Gremlin and serves as the foundation by which all other Gremlin language variants should emulate. As the Gremlin Traversal Machine that processes Gremlin queries is also written in Java, it can be used in all three connection methods described in the <> Section. [source,xml] ---- org.apache.tinkerpop gremlin-core x.y.z org.apache.tinkerpop gremlin-driver x.y.z ---- === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. For <> mode, this involves first creating a `Graph` and then spawning the `GraphTraversalSource`: [source,java] ---- Graph graph = ...; GraphTraversalSource g = graph.traversal(); ---- Using ""g"" it is then possible to start writing Gremlin. The ""g"" allows for the setting of many configuration options which affect traversal execution. The <> Section describes some of these options and some are only suitable with <> style usage. For remote options however there are some added configurations to consider and this section looks to address those. When connecting to <> or <> it is possible to configure the `DriverRemoteConnection` manually as shown in earlier examples where the host and port are provided as follows: [source,java] ---- GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(""localhost"",8182,""g"")); ---- It is also possible to create it from a configuration. The most basic way to do so involves the following line of code: [source,java] ---- GraphTraversalSource g = traversal().withRemote('conf/remote-graph.properties'); ---- The `remote-graph.properties` file simply provides connection information to the `GraphTraversalSource` which is used to configure a `RemoteConnection`. That file looks like this: [source,text] ---- gremlin.remote.remoteConnectionClass=org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection gremlin.remote.driver.clusterFile=conf/remote-objects.yaml gremlin.remote.driver.sourceName=g ---- The `RemoteConnection` is an interface that provides the transport mechanism for ""g"" and makes it possible to for that mechanism to be altered (typically by graph providers who have their own protocols). TinkerPop provides one such implementation called the `DriverRemoteConnection` which enables transport over Gremlin Server protocols using the TinkerPop driver. The driver is configured by the specified `gremlin.remote.driver.clusterFile` and the local ""g"" is bound to the `GraphTraversalSource` on the remote end with `gremlin.remote.driver.sourceName` which in this case is also ""g"". There are other ways to configure the traversal using `withRemote()` as it has other overloads. It can take an Apache Commons `Configuration` object which would have keys similar to those shown in the properties file and it can also take a `RemoteConnection` instance directly. The latter is interesting in that it means it is possible to programmatically construct all aspects of the `RemoteConnection`. For TinkerPop usage, that might mean directly constructing the `DriverRemoteConnection` and the driver instance that supplies the transport mechanism. For example, the command shown above could be re-written using programmatic construction as follows: [source,java] ---- Cluster cluster = Cluster.open(); GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(cluster, ""g"")); ---- Please consider the following example: [gremlin-groovy] ---- g = traversal().withRemote('conf/remote-graph.properties') g.V().elementMap() g.close() ---- [source,java] ---- GraphTraversalSource g = traversal().withRemote(""conf/remote-graph.properties""); List list = g.V().elementMap(); g.close(); ---- Note the call to `close()` above. The call to `withRemote()` internally instantiates a connection via the driver that can only be released by ""closing"" the `GraphTraversalSource`. It is important to take that step to release resources created in that step. If working with multiple remote `TraversalSource` instances it is more efficient to construct `Cluster` and `Client objects and then re-use them. [gremlin-groovy] ---- cluster = Cluster.open('conf/remote-objects.yaml') client = cluster.connect() g = traversal().withRemote(DriverRemoteConnection.using(client, ""g"")) g.V().elementMap() g.close() client.close() cluster.close() ---- If the `Client` instance is supplied externally, as is shown above, then it is not closed implicitly by the close of ""g"". Closing ""g"" will have no effect on ""client"" or ""cluster"". When supplying them externally, the `Client` and `Cluster` objects must also be closed explicitly. It's worth noting that the close of a `Cluster` will close all `Client` instances spawned by the `Cluster`. IMPORTANT: Bytecode-based traversals use the `TraversalOpProcessor` in Gremlin Server which requires a cache to enable the retrieval of side-effects (if the `Traversal` produces any). That cache can be configured (e.g. controlling eviction times and sizing) in the Gremlin Server configuration file as described <>. Some connection options can also be set on individual requests made through the Java driver using `with()` step on the `TraversalSource`. For instance to set request timeout to 500 milliseconds: [source,java] ---- GraphTraversalSource g = traversal().withRemote(conf); List vertices = g.with(Tokens.ARGS_EVAL_TIMEOUT, 500L).V().out(""knows"").toList() ---- [[java-imports]] === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the common functionality required to use Gremlin: [source,java] ---- import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.IO; import static org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource.traversal; import static org.apache.tinkerpop.gremlin.process.traversal.Operator.*; import static org.apache.tinkerpop.gremlin.process.traversal.Order.*; import static org.apache.tinkerpop.gremlin.process.traversal.P.*; import static org.apache.tinkerpop.gremlin.process.traversal.Pop.*; import static org.apache.tinkerpop.gremlin.process.traversal.SackFunctions.*; import static org.apache.tinkerpop.gremlin.process.traversal.Scope.*; import static org.apache.tinkerpop.gremlin.process.traversal.TextP.*; import static org.apache.tinkerpop.gremlin.structure.Column.*; import static org.apache.tinkerpop.gremlin.structure.Direction.*; import static org.apache.tinkerpop.gremlin.structure.T.*; import static org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__.*; ---- === Configuration The following table describes the various configuration options for the Gremlin Driver: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |connectionPool.channelizer |The fully qualified classname of the client `Channelizer` that defines how to connect to the server. |`Channelizer.WebSocketChannelizer` |connectionPool.enableSsl |Determines if SSL should be enabled or not. If enabled on the server then it must be enabled on the client. |false |connectionPool.keepAliveInterval |Length of time in milliseconds to wait on an idle connection before sending a keep-alive request. Set to zero to disable this feature. |180000 |connectionPool.keyStore |The private key in JKS or PKCS#12 format. |_none_ |connectionPool.keyStorePassword |The password of the `keyStore` if it is password-protected. |_none_ |connectionPool.keyStoreType |`JKS` (Java 8 default) or `PKCS12` (Java 9+ default)|_none_ |connectionPool.maxContentLength |The maximum length in bytes that a message can be sent to the server. This number can be no greater than the setting of the same name in the server configuration. |65536 |connectionPool.maxInProcessPerConnection |The maximum number of in-flight requests that can occur on a connection. |4 |connectionPool.maxSimultaneousUsagePerConnection |The maximum number of times that a connection can be borrowed from the pool simultaneously. |16 |connectionPool.maxSize |The maximum size of a connection pool for a host. |8 |connectionPool.maxWaitForConnection |The amount of time in milliseconds to wait for a new connection before timing out. |3000 |connectionPool.maxWaitForClose |The amount of time in milliseconds to wait for pending messages to be returned from the server before closing the connection. |3000 |connectionPool.minInProcessPerConnection |The minimum number of in-flight requests that can occur on a connection. |1 |connectionPool.minSimultaneousUsagePerConnection |The maximum number of times that a connection can be borrowed from the pool simultaneously. |8 |connectionPool.minSize |The minimum size of a connection pool for a host. |2 |connectionPool.reconnectInterval |The amount of time in milliseconds to wait before trying to reconnect to a dead host. |1000 |connectionPool.resultIterationBatchSize |The override value for the size of the result batches to be returned from the server. |64 |connectionPool.sslCipherSuites |The list of JSSE ciphers to support for SSL connections. If specified, only the ciphers that are listed and supported will be enabled. If not specified, the JVM default is used. |_none_ |connectionPool.sslEnabledProtocols |The list of SSL protocols to support for SSL connections. If specified, only the protocols that are listed and supported will be enabled. If not specified, the JVM default is used. |_none_ |connectionPool.sslSkipCertValidation |Configures the `TrustManager` to trust all certs without any validation. Should not be used in production.|false |connectionPool.trustStore |File location for a SSL Certificate Chain to use when SSL is enabled. If this value is not provided and SSL is enabled, the default `TrustManager` will be used. |_none_ |connectionPool.trustStorePassword |The password of the `trustStore` if it is password-protected |_none_ |connectionPool.validationRequest |A script that is used to test server connectivity. A good script to use is one that evaluates quickly and returns no data. The default simply returns an empty string, but if a graph is required by a particular provider, a good traversal might be `g.inject()`. |_''_ |hosts |The list of hosts that the driver will connect to. |localhost |jaasEntry |Sets the `AuthProperties.Property.JAAS_ENTRY` properties for authentication to Gremlin Server. |_none_ |nioPoolSize |Size of the pool for handling request/response operations. |available processors |password |The password to submit on requests that require authentication. |_none_ |path |The URL path to the Gremlin Server. |_/gremlin_ |port |The port of the Gremlin Server to connect to. The same port will be applied for all hosts. |8192 |protocol |Sets the `AuthProperties.Property.PROTOCOL` properties for authentication to Gremlin Server. |_none_ |serializer.className |The fully qualified class name of the `MessageSerializer` that will be used to communicate with the server. Note that the serializer configured on the client should be supported by the server configuration. |_none_ |serializer.config |A `Map` of configuration settings for the serializer. |_none_ |username |The username to submit on requests that require authentication. |_none_ |workerPoolSize |Size of the pool for handling background work. |available processors * 2 |========================================================= Please see the link:https://tinkerpop.apache.org/javadocs/x.y.z/core/org/apache/tinkerpop/gremlin/driver/Cluster.Builder.html[Cluster.Builder javadoc] to get more information on these settings. === Serialization Remote systems like Gremlin Server and Remote Gremlin Providers respond to requests made in a particular serialization format and respond by serializing results to some format to be interpreted by the client. For JVM-based languages, there are three options for serialization: Gryo, GraphSON and GraphBinary. It is important that the client and server have the same serializers configured in the same way or else one or the other will experience serialization exceptions and fail to always communicate. Discrepancy in serializer registration between client and server can happen fairly easily as different graph systems may automatically include serializers on the server-side, thus leaving the client to be configured manually. As an example: [source,java] ---- IoRegistry registry = ...; // an IoRegistry instance exposed by a specific graph provider TypeSerializerRegistry typeSerializerRegistry = TypeSerializerRegistry.build().addRegistry(registry).create(); MessageSerializer serializer = new GraphBinaryMessageSerializerV1(typeSerializerRegistry); Cluster cluster = Cluster.build(). serializer(serializer). create(); Client client = cluster.connect(); GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(client, ""g"")); ---- The `IoRegistry` tells the serializer what classes from the graph provider to auto-register during serialization. Gremlin Server roughly uses this same approach when it configures its serializers, so using this same model will ensure compatibility when making requests. Obviously, it is possible to switch to GraphSON or Gryo by using the appropriate `MessageSerializer` (e.g. `GraphSONMessageSerializerV3d0` or `GryoMessageSerializerV3d0` respectively) in the same way and building that into the `Cluster` object. NOTE: Gryo is no longer the preferred binary serialization format for Gremlin Server - please prefer GraphBinary. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. In Gremlin-Java and with <> usage, lambdas can be leveraged directly: [source,java] ---- g.V().out(""knows"").map(t -> t.get().value(""name"") + "" is the friend name"") <1> g.V().out(""knows"").sideEffect(System.out::println) <2> g.V().as(""a"").out(""knows"").as(""b"").select(""b"").by((Function) v -> v.value(""name"").length()) <3> ---- <1> A Java `Function` is used to map a `Traverser` to an object `E`. <2> Gremlin steps that take consumer arguments can be passed Java method references. <3> Gremlin-Java may sometimes require explicit lambda typing when types can not be automatically inferred. When sending traversals remotely to <> or <>, the static methods of `Lambda` should be used and should denote a particular JSR-223 `ScriptEngine` that is available on the remote end (typically, this is Groovy). `Lambda` creates a string-based lambda that is then converted into a lambda/closure/anonymous-function/etc. by the respective lambda language's JSR-223 `ScriptEngine` implementation. [source,java] ---- g.V().out(""knows"").map(Lambda.function(""it.get().value('name') + ' is the friend name'"")) g.V().out(""knows"").sideEffect(Lambda.consumer(""println it"")) g.V().as(""a"").out(""knows"").as(""b"").select(""b"").by(Lambda.function(""it.value('name').length()"")) ---- Finally, Gremlin `Bytecode` that includes lambdas requires that the traversal be processed by the `ScriptEngine`. To avoid continued recompilation costs, it supports the encoding of bindings, which allow Gremlin Server to cache traversals that will be reused over and over again save that some parameterization may change. Thus, instead of translating, compiling, and then executing each submitted bytecode request, it is possible to simply execute. To express bindings in Java, use `Bindings`. [source,java] ---- b = Bindings.instance() g.V(b.of('id',1)).out('created').values('name').map{t -> ""name: "" + t.get() } g.V(b.of('id',4)).out('created').values('name').map{t -> ""name: "" + t.get() } g.V(b.of('id',4)).out('created').values('name').getBytecode() g.V(b.of('id',4)).out('created').values('name').getBytecode().getBindings() cluster.close() ---- Both traversals are abstractly defined as `g.V(id).out('created').values('name').map{t -> ""name: "" + t.get() }` and thus, the first submission can be cached for faster evaluation on the next submission. WARNING: It is generally advised to avoid lambda usage. Please consider <> for more information. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. image:gremlin-java.png[width=175,float=left] TinkerPop comes equipped with a reference client for Java-based applications. It is referred to as `gremlin-driver`, which enables applications to send requests to Gremlin Server and get back results. Gremlin scripts are sent to the server from a `Client` instance. A `Client` is created as follows: [source,java] ---- Cluster cluster = Cluster.open(); <1> Client client = cluster.connect(); <2> ---- <1> Opens a reference to `localhost` - note that there are many configuration options available in defining a `Cluster` object. <2> Creates a `Client` given the configuration options of the `Cluster`. Once a `Client` instance is ready, it is possible to issue some Gremlin Groovy scripts: [source,java] ---- ResultSet results = client.submit(""[1,2,3,4]""); <1> results.stream().map(i -> i.get(Integer.class) * 2); <2> CompletableFuture> results = client.submit(""[1,2,3,4]"").all(); <3> CompletableFuture future = client.submitAsync(""[1,2,3,4]""); <4> Map params = new HashMap<>(); params.put(""x"",4); client.submit(""[1,2,3,x]"", params); <5> ---- <1> Submits a script that simply returns a `List` of integers. This method blocks until the request is written to the server and a `ResultSet` is constructed. <2> Even though the `ResultSet` is constructed, it does not mean that the server has sent back the results (or even evaluated the script potentially). The `ResultSet` is just a holder that is awaiting the results from the server. In this case, they are streamed from the server as they arrive. <3> Submit a script, get a `ResultSet`, then return a `CompletableFuture` that will be called when all results have been returned. <4> Submit a script asynchronously without waiting for the request to be written to the server. <5> Parameterized request are considered the most efficient way to send Gremlin to the server as they can be cached, which will boost performance and reduce resources required on the server. ==== Per Request Settings There are a number of overloads to `Client.submit()` that accept a `RequestOptions` object. The `RequestOptions` provide a way to include options that are specific to the request made with the call to `submit()`. A good use-case for this feature is to set a per-request override to the `evaluationTimeout` so that it only applies to the current request. [source,java] ---- Cluster cluster = Cluster.open(); Client client = cluster.connect(); RequestOptions options = RequestOptions.build().timeout(500).create(); List result = client.submit(""g.V()"", options).all().get(); ---- ==== Aliases Scripts submitted to Gremlin Server automatically have the globally configured `Graph` and `TraversalSource` instances made available to them. Therefore, if Gremlin Server configures two `TraversalSource` instances called ""g1"" and ""g2"" a script can simply reference them directly as: [source,java] ---- client.submit(""g1.V()"") client.submit(""g2.V()"") ---- While this is an acceptable way to submit scripts, it has the downside of forcing the client to encode the server-side variable name directly into the script being sent. If the server configuration ever changed such that ""g1"" became ""g100"", the client-side code might have to see a significant amount of change. Decoupling the script code from the server configuration can be managed by the `alias` method on `Client` as follows: [source,java] ---- Client g1Client = client.alias(""g1"") Client g2Client = client.alias(""g2"") g1Client.submit(""g.V()"") g2Client.submit(""g.V()"") ---- The above code demonstrates how the `alias` method can be used such that the script need only contain a reference to ""g"" and ""g1"" and ""g2"" are automatically rebound into ""g"" on the server-side. [[gremlin-java-dsl]] === Domain Specific Languages Creating a <> (DSL) in Java requires the `@GremlinDsl` Java annotation in `gremlin-core`. This annotation should be applied to a ""DSL interface"" that extends `GraphTraversal.Admin`: [source,java] ---- @GremlinDsl public interface SocialTraversalDsl extends GraphTraversal.Admin { } ---- IMPORTANT: The name of the DSL interface should be suffixed with ""TraversalDSL"". All characters in the interface name before that become the ""name"" of the DSL. In this interface, define the methods that the DSL will be composed of: [source,java] ---- @GremlinDsl public interface SocialTraversalDsl extends GraphTraversal.Admin { public default GraphTraversal knows(String personName) { return out(""knows"").hasLabel(""person"").has(""name"", personName); } public default GraphTraversal youngestFriendsAge() { return out(""knows"").hasLabel(""person"").values(""age"").min(); } public default GraphTraversal createdAtLeast(int number) { return outE(""created"").count().is(P.gte(number)); } } ---- IMPORTANT: Follow the TinkerPop convention of using `` in naming generics as those conventions are taken into account when generating the anonymous traversal class. The processor attempts to infer the appropriate type parameters when generating the anonymous traversal class. If it cannot do it correctly, it is possible to avoid the inference by using the `GremlinDsl.AnonymousMethod` annotation on the DSL method. It allows explicit specification of the types to use. The `@GremlinDsl` annotation is used by the link:https://docs.oracle.com/javase/8/docs/api/index.html?javax/annotation/processing/Processor.html[Java Annotation Processor] to generate the boilerplate class structure required to properly use the DSL within the TinkerPop framework. These classes can be generated and maintained by hand, but it would be time consuming, monotonous and error-prone to do so. Typically, the Java compilation process is automatically configured to detect annotation processors on the classpath and will automatically use them when found. If that does not happen, it may be necessary to make configuration changes to the build to allow for the compilation process to be aware of the following `javax.annotation.processing.Processor` implementation: [source,java] ---- org.apache.tinkerpop.gremlin.process.traversal.dsl.GremlinDslProcessor ---- The annotation processor will generate several classes for the DSL: * `SocialTraversal` - A `Traversal` interface that extends the `SocialTraversalDsl` proxying methods to its underlying interfaces (such as `GraphTraversal`) to instead return a `SocialTraversal` * `DefaultSocialTraversal` - A default implementation of `SocialTraversal` (typically not used directly by the user) * `SocialTraversalSource` - Spawns `DefaultSocialTraversal` instances. * `__` - Spawns anonymous `DefaultSocialTraversal` instances. Using the DSL then just involves telling the `Graph` to use it: [source,java] ---- SocialTraversalSource social = graph.traversal(SocialTraversalSource.class); social.V().has(""name"",""marko"").knows(""josh""); ---- The `SocialTraversalSource` can also be customized with DSL functions. As an additional step, include a class that extends from `GraphTraversalSource` and with a name that is suffixed with ""TraversalSourceDsl"". Include in this class, any custom methods required by the DSL: [source,java] ---- public class SocialTraversalSourceDsl extends GraphTraversalSource { public SocialTraversalSourceDsl(Graph graph, TraversalStrategies traversalStrategies) { super(graph, traversalStrategies); } public SocialTraversalSourceDsl(Graph graph) { super(graph); } public GraphTraversal persons(String... names) { GraphTraversalSource clone = this.clone(); // Manually add a ""start"" step for the traversal in this case the equivalent of V(). GraphStep is marked // as a ""start"" step by passing ""true"" in the constructor. clone.getBytecode().addStep(GraphTraversal.Symbols.V); GraphTraversal traversal = new DefaultGraphTraversal<>(clone); traversal.asAdmin().addStep(new GraphStep<>(traversal.asAdmin(), Vertex.class, true)); traversal = traversal.hasLabel(""person""); if (names.length > 0) traversal = traversal.has(""name"", P.within(names)); return traversal; } } ---- Then, back in the `SocialTraversal` interface, update the `GremlinDsl` annotation with the `traversalSource` argument to point to the fully qualified class name of the `SocialTraversalSourceDsl`: [source,java] ---- @GremlinDsl(traversalSource = ""com.company.SocialTraversalSourceDsl"") public interface SocialTraversalDsl extends GraphTraversal.Admin { ... } ---- It is then possible to use the `persons()` method to start traversals: [source,java] ---- SocialTraversalSource social = graph.traversal(SocialTraversalSource.class); social.persons(""marko"").knows(""josh""); ---- NOTE: Using Maven, as shown in the `gremlin-archetype-dsl` module, makes developing DSLs with the annotation processor straightforward in that it sets up appropriate paths to the generated code automatically. anchor:java-application-examples[] [[gremlin-archetypes]] === Application Examples The available link:https://maven.apache.org/guides/introduction/introduction-to-archetypes.html[Maven archetypes] are as follows: * `gremlin-archetype-dsl` - An example project that demonstrates how to build Domain Specific Languages with Gremlin in Java. * `gremlin-archetype-server` - An example project that demonstrates the basic structure of a <> project, how to connect with the Gremlin Driver, and how to embed Gremlin Server in a testing framework. * `gremlin-archetype-tinkergraph` - A basic example of how to structure a TinkerPop project with Maven. Use Maven to generate these example projects with a command like: [source,shell] $ mvn archetype:generate -DarchetypeGroupId=org.apache.tinkerpop -DarchetypeArtifactId=gremlin-archetype-server \\ -DarchetypeVersion=x.y.z -DgroupId=com.my -DartifactId=app -Dversion=0.1 -DinteractiveMode=false This command will generate a new Maven project in a directory called ""app"" with a `pom.xml` specifying a `groupId` of `com.my`. Please see the `README.asciidoc` in the root of each generated project for information on how to build and execute it. [[gremlin-groovy]] == Gremlin-Groovy image:gremlin-groovy-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Groovy implements Gremlin within the link:http://groovy.apache.org[Apache Groovy] language. As a JVM-based language variant, Gremlin-Groovy is backed by Gremlin-Java constructs. Moreover, given its scripting nature, Gremlin-Groovy serves as the language of <> and <>. [source,groovy] ---- compile group: 'org.apache.tinkerpop', name: 'gremlin-core', version: '3.3.4' compile group: 'org.apache.tinkerpop', name: 'gremlin-driver', version: '3.3.4' ---- [[gremlin-groovy-differences]] === Differences In Groovy, `as`, `in`, and `not` are reserved words. Gremlin-Groovy does not allow these steps to be called statically from the anonymous traversal `+__+` and therefore, must always be prefixed with `+__.+` For instance: `+g.V().as('a').in().as('b').where(__.not(__.as('a').out().as('b')))+` [[gremlin-python]] == Gremlin-Python image:gremlin-python-drawing.png[width=130,float=right] Apache TinkerPop's Gremlin-Python implements Gremlin within the link:https://www.python.org/[Python] language and can be used on any Python virtual machine including the popular link:https://en.wikipedia.org/wiki/CPython[CPython] machine. Python's syntax has the same constructs as Java including ""dot notation"" for function chaining (`a.b.c`), round bracket function arguments (`a(b,c)`), and support for global namespaces (`a(b())` vs `a(__.b())`). As such, anyone familiar with Gremlin-Java will immediately be able to work with Gremlin-Python. Moreover, there are a few added constructs to Gremlin-Python that make traversals a bit more succinct. To install Gremlin-Python, use Python's link:https://en.wikipedia.org/wiki/Pip_(package_manager)[pip] package manager. [source,bash] ---- pip install gremlinpython ---- === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the anonymous `traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,python] ---- g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g')) ---- If you need to send additional headers in the websockets connection, you can pass an optional `headers` parameter to the `DriverRemoteConnection` constructor. [source,python] ---- g = traversal().withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g',headers={'Header':'Value'})) ---- NOTE: If connecting from an inherently single-threaded Python process where blocking while waiting for Gremlin traversals to complete is acceptable, it might be helpful to set `pool_size` and `max_workers` parameters to 1. See the <> section just below. Examples where this could apply are serverless cloud functions or WSGI worker processes. [[python-imports]] === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,python] ---- from gremlin_python import statics from gremlin_python.process.anonymous_traversal import traversal from gremlin_python.process.graph_traversal import __ from gremlin_python.process.strategies import * from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.process.traversal import T from gremlin_python.process.traversal import Order from gremlin_python.process.traversal import Cardinality from gremlin_python.process.traversal import Column from gremlin_python.process.traversal import Direction from gremlin_python.process.traversal import Operator from gremlin_python.process.traversal import P from gremlin_python.process.traversal import Pop from gremlin_python.process.traversal import Scope from gremlin_python.process.traversal import Barrier from gremlin_python.process.traversal import Bindings from gremlin_python.process.traversal import WithOptions ---- These can be used analogously to how they are used in Gremlin-Java. [source,python] ---- >>> g.V().hasLabel('person').has('age',P.gt(30)).order().by('age',Order.desc).toList() [v[6], v[4]] ---- Moreover, by importing the `statics` of Gremlin-Python, the class prefixes can be omitted. [source,python] ---- >>> statics.load_statics(globals()) ---- With statics loaded its possible to represent the above traversal as below. [source,python] ---- >>> g.V().hasLabel('person').has('age',gt(30)).order().by('age',desc).toList() [v[6], v[4]] ---- Finally, statics includes all the `+__+`-methods and thus, anonymous traversals like `+__.out()+` can be expressed as below. That is, without the `+__+`-prefix. [source,python] ---- >>> g.V().repeat(out()).times(2).name.fold().toList() [['ripple', 'lop']] ---- [[python-configuration]] === Configuration The following table describes the various configuration options for the Gremlin-Python Driver. They can be passed to the `Client` or `DriverRemoteConnection` instance as keyword arguments: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |protocol_factory |A callable that returns an instance of `AbstractBaseProtocol`. |`gremlin_python.driver.protocol.GremlinServerWSProtocol` |transport_factory |A callable that returns an instance of `AbstractBaseTransport`. |`gremlin_python.driver.tornado.transport.TornadoTransport` |pool_size |The number of connections used by the pool. |4 |max_workers |Maximum number of worker threads. |Number of CPUs * 5 |message_serializer |The message serializer implementation.|`gremlin_python.driver.serializer.GraphSONMessageSerializer` |password |The password to submit on requests that require authentication. |"""" |username |The username to submit on requests that require authentication. |"""" |session | A unique string-based identifier (typically a UUID) to enable a <>. This is not a valid configuration for `DriverRemoteConnection`. |None |========================================================= === Traversal Strategies In order to add and remove <> from a traversal source, Gremlin-Python has a `TraversalStrategy` class along with a collection of subclasses that mirror the standard Gremlin-Java strategies. [source,python] ---- >>> g = g.withStrategies(SubgraphStrategy(vertices=hasLabel('person'),edges=has('weight',gt(0.5)))) >>> g.V().name.toList() ['marko', 'vadas', 'josh', 'peter'] >>> g.V().outE().elementMap().toList() [{: 8, : 'knows', : {: 4, : 'person'}, : {: 1, : 'person'}, 'weight': 1.0}] >>> g = g.withoutStrategies(SubgraphStrategy) >>> g.V().name.toList() ['marko', 'vadas', 'lop', 'josh', 'ripple', 'peter'] >>> g.V().outE().elementMap().toList() [{: 9, : 'created', : {: 3, : 'software'}, : {: 1, : 'person'}, 'weight': 0.4}, {: 7, : 'knows', : {: 2, : 'person'}, : {: 1, : 'person'}, 'weight': 0.5}, {: 8, : 'knows', : {: 4, : 'person'}, : {: 1, : 'person'}, 'weight': 1.0}, {: 10, : 'created', : {: 5, : 'software'}, : {: 4, : 'person'}, 'weight': 1.0}, {: 11, : 'created', : {: 3, : 'software'}, : {: 4, : 'person'}, 'weight': 0.4}, {: 12, : 'created', : {: 3, : 'software'}, : {: 6, : 'person'}, 'weight': 0.2}] >>> g = g.withComputer(workers=2,vertices=has('name','marko')) >>> g.V().name.toList() ['marko'] >>> g.V().outE().valueMap().with_(WithOptions.tokens).toList() [{: 9, : 'created', 'weight': 0.4}, {: 7, : 'knows', 'weight': 0.5}, {: 8, : 'knows', 'weight': 1.0}] ---- NOTE: Many of the `TraversalStrategy` classes in Gremlin-Python are proxies to the respective strategy on Apache TinkerPop's JVM-based Gremlin traversal machine. As such, their `apply(Traversal)` method does nothing. However, the strategy is encoded in the Gremlin-Python bytecode and transmitted to the Gremlin traversal machine for re-construction machine-side. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. In Gremlin-Python, a link:https://docs.python.org/2/reference/expressions.html#lambda[Python lambda] should be represented as a zero-arg callable that returns a string representation of a lambda. The lambda should be written as a `Gremlin-Groovy`string. When the lambda is represented in `Bytecode` its language is encoded such that the remote connection host can infer which translator and ultimate execution engine to use. [source,python] ---- >>> g.V().out().map(lambda: ""it.get().value('name').length()"").sum().toList() [24] ---- TIP: When running into situations where Groovy cannot properly discern a method signature based on the `Lambda` instance created, it will help to fully define the closure in the lambda expression - so rather than `lambda: (""it.get().value(""name')"",""gremlin-groovy"")`, prefer `lambda: (""x -> x.get().value(""name""),""gremlin-groovy"")`. Finally, Gremlin `Bytecode` that includes lambdas requires that the traversal be processed by the `ScriptEngine`. To avoid continued recompilation costs, it supports the encoding of bindings, which allow a remote engine to to cache traversals that will be reused over and over again save that some parameterization may change. Thus, instead of translating, compiling, and then executing each submitted bytecode, it is possible to simply execute. [source,python] ---- >>> g.V(Bindings.of('x',1)).out('created').map(lambda: ""it.get().value('name').length()"").sum().toList() [3] >>> g.V(Bindings.of('x',4)).out('created').map(lambda: ""it.get().value('name').length()"").sum().toList() [9] ---- WARNING: As explained throughout the documentation, when possible <> lambdas. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. The `Client` class implementation/interface is based on the Java Driver, with some restrictions. Most notably, Gremlin-Python does not yet implement the `Cluster` class. Instead, `Client` is instantiated directly. Usage is as follows: [source,python] ---- from gremlin_python.driver import client <1> client = client.Client('ws://localhost:8182/gremlin', 'g') <2> ---- <1> Import the Gremlin-Python `client` module. <2> Opens a reference to `localhost` - note that there are various configuration options that can be passed to the `Client` object upon instantiation as keyword arguments. Once a `Client` instance is ready, it is possible to issue some Gremlin: [source,python] ---- result_set = client.submit(""[1,2,3,4]"") <1> future_results = result_set.all() <2> results = future_results.result() <3> assert results == [1, 2, 3, 4] <4> future_result_set = client.submitAsync(""[1,2,3,4]"") <5> result_set = future_result_set.result() <6> result = result_set.one() <7> assert results == [1, 2, 3, 4] <8> assert result_set.done.done() <9> client.close() <10> ---- <1> Submit a script that simply returns a `List` of integers. This method blocks until the request is written to the server and a `ResultSet` is constructed. <2> Even though the `ResultSet` is constructed, it does not mean that the server has sent back the results (or even evaluated the script potentially). The `ResultSet` is just a holder that is awaiting the results from the server. The `all` method returns a `concurrent.futures.Future` that resolves to a list when it is complete. <3> Block until the the script is evaluated and results are sent back by the server. <4> Verify the result. <5> Submit the same script to the server but don't block. <6> Wait until request is written to the server and `ResultSet` is constructed. <7> Read a single result off the result stream. <8> Again, verify the result. <9> Verify that the all results have been read and stream is closed. <10> Close client and underlying pool connections. [[gremlin-python-dsl]] === Domain Specific Languages Writing a Gremlin <> (DSL) in Python simply requires direct extension of several classes: * `GraphTraversal` - which exposes the various steps used in traversal writing * `__` - which spawns anonymous traversals from steps * `GraphTraversalSource` - which spawns `GraphTraversal` instances The Social DSL based on the link:https://tinkerpop.apache.org/docs/current/images/tinkerpop-modern.png[""modern"" toy graph] might look like this: [source,python] ---- class SocialTraversal(GraphTraversal): def knows(self, person_name): return self.out(""knows"").hasLabel(""person"").has(""name"", person_name) def youngestFriendsAge(self): return self.out(""knows"").hasLabel(""person"").values(""age"").min() def createdAtLeast(self, number): return self.outE(""created"").count().is_(P.gte(number)) class __(AnonymousTraversal): graph_traversal = SocialTraversal @classmethod def knows(cls, *args): return cls.graph_traversal(None, None, Bytecode()).knows(*args) @classmethod def youngestFriendsAge(cls, *args): return cls.graph_traversal(None, None, Bytecode()).youngestFriendsAge(*args) @classmethod def createdAtLeast(cls, *args): return cls.graph_traversal(None, None, Bytecode()).createdAtLeast(*args) class SocialTraversalSource(GraphTraversalSource): def __init__(self, *args, **kwargs): super(SocialTraversalSource, self).__init__(*args, **kwargs) self.graph_traversal = SocialTraversal def persons(self, *args): traversal = self.get_graph_traversal() traversal.bytecode.add_step(""V"") traversal.bytecode.add_step(""hasLabel"", ""person"") if len(args) > 0: traversal.bytecode.add_step(""has"", ""name"", P.within(args)) return traversal ---- NOTE: The `AnonymousTraversal` class above is just an alias for `+__+` as in `+from gremlin_python.process.graph_traversal import __ as AnonymousTraversal+` Using the DSL is straightforward and just requires that the graph instance know the `SocialTraversalSource` should be used: [source,python] ---- social = Graph().traversal(SocialTraversalSource).withRemote(DriverRemoteConnection('ws://localhost:8182/gremlin','g')) social.persons(""marko"").knows(""josh"") social.persons(""marko"").youngestFriendsAge() social.persons().filter(__.createdAtLeast(2)).count() ---- === Syntactic Sugar Python supports meta-programming and operator overloading. There are three uses of these techniques in Gremlin-Python that makes traversals a bit more concise. [source,python] ---- >>> g.V().both()[1:3].toList() [v[2], v[4]] >>> g.V().both()[1].toList() [v[2]] >>> g.V().both().name.toList() ['lop', 'lop', 'lop', 'vadas', 'josh', 'josh', 'josh', 'marko', 'marko', 'marko', 'peter', 'ripple'] ---- [[gremlin-python-differences]] === Differences In situations where Python reserved words and global functions overlap with standard Gremlin steps and tokens, those bits of conflicting Gremlin get an underscore appended as a suffix: *Steps* - <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <>, <> *Tokens* - <> === Limitations * Traversals that return a `Set` *might* be coerced to a `List` in Python. In the case of Python, number equality is different from JVM languages which produces different `Set` results when those types are in use. When this case is detected during deserialization, the `Set` is coerced to a `List` so that traversals return consistent results within a collection across different languages. If a `Set` is needed then convert `List` results to `Set` manually. * Gremlin is capable of returning `Dictionary` results that use non-hashable keys (e.g. Dictionary as a key) and Python does not support that at a language level. Gremlin that returns such results will need to be re-written to avoid that. === Application Examples The TinkerPop source code contains a simple Python script that shows a basic example of how gremlinpython works. It can be found in GitHub link:https://github.com/apache/tinkerpop/tree/xx.yy.zz/gremlin-python/src/main/python/example.py[here] and is designed to work best with a running <> configured with the default `conf/gremlin-server.yaml` file as included with the standard release packaging. [source,shell] ---- pip install gremlinpython pip install tornado python example.py ---- anchor:gremlin-DotNet[] [[gremlin-dotnet]] == Gremlin.Net image:gremlin-dotnet-logo.png[width=371,float=right] Apache TinkerPop's Gremlin.Net implements Gremlin within the C# language. It targets .NET Standard and can therefore be used on different operating systems and with different .NET frameworks, such as .NET Framework and link:https://www.microsoft.com/net/core[.NET Core]. Since the C# syntax is very similar to that of Java, it should be very easy to switch between Gremlin-Java and Gremlin.Net. The only major syntactical difference is that all method names in Gremlin.Net use PascalCase as opposed to camelCase in Gremlin-Java in order to comply with .NET conventions. [source,powershell] nuget install Gremlin.Net === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the `AnonymousTraversalSource.traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=connecting] ---- === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=commonImports] ---- === Configuration The connection properties for the Gremlin.Net driver can be passed to the `GremlinServer` instance as keyword arguments: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |hostname |The hostname that the driver will connect to. |localhost |port |The port on which Gremlin Server can be reached. |8182 |enableSsl |Determines if SSL should be enabled or not. If enabled on the server then it must be enabled on the client. |false |username |The username to submit on requests that require authentication. |_none_ |password |The password to submit on requests that require authentication. |_none_ |========================================================= ==== Connection Pool It is also possible to configure the `ConnectionPool` of the Gremlin.Net driver. These configuration options can be set as properties on the `ConnectionPoolSettings` instance that can be passed to the `GremlinClient`: [width=""100%"",cols=""3,10,^2"",options=""header""] |========================================================= |Key |Description |Default |PoolSize |The size of the connection pool. |4 |MaxInProcessPerConnection |The maximum number of in-flight requests that can occur on a connection. |32 |ReconnectionAttempts |The number of attempts to get an open connection from the pool to submit a request. |4 |ReconnectionBaseDelay |The base delay used for the exponential backoff for the reconnection attempts. |1 s |========================================================= A `NoConnectionAvailableException` is thrown if all connections have reached the `MaxInProcessPerConnection` limit when a new request comes in. A `ServerUnavailableException` is thrown if no connection is available to the server to submit a request after `ReconnectionAttempts` retries. ==== Serialization The Gremlin.Net driver uses by default GraphSON 3.0 but it is also possible to use GraphSON 2.0 which can be necessary when the server does not support GraphSON 3.0 yet: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=serialization] ---- === Traversal Strategies In order to add and remove traversal strategies from a traversal source, Gremlin.Net has an `AbstractTraversalStrategy` class along with a collection of subclasses that mirror the standard Gremlin-Java strategies. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=traversalStrategies] ---- NOTE: Many of the TraversalStrategy classes in Gremlin.Net are proxies to the respective strategy on Apache TinkerPop’s JVM-based Gremlin traversal machine. As such, their `Apply(ITraversal)` method does nothing. However, the strategy is encoded in the Gremlin.Net bytecode and transmitted to the Gremlin traversal machine for re-construction machine-side. === The Lambda Solution Supporting link:https://en.wikipedia.org/wiki/Anonymous_function[anonymous functions] across languages is difficult as most languages do not support lambda introspection and thus, code analysis. While Gremlin.Net doesn't support C# lambdas, it is still able to represent lambdas in other languages. When the lambda is represented in `Bytecode` its language is encoded such that the remote connection host can infer which translator and ultimate execution engine to use. [source,csharp] ---- g.V().Out().Map(Lambda.Groovy(""it.get().value('name').length()"")).Sum().ToList(); <1> g.V().Out().Map(Lambda.Python(""lambda x: len(x.get().value('name'))"")).Sum().ToList(); <2> ---- <1> `Lambda.Groovy()` can be used to create a Groovy lambda. <2> `Lambda.Python()` can be used to create a Python lambda. The `ILambda` interface returned by these two methods inherits interfaces like `IFunction` and `IPredicate` that mirror their Java counterparts which makes it possible to use lambdas with Gremlin.Net for the same steps as in Gremlin-Java. TIP: When running into situations where Groovy cannot properly discern a method signature based on the `Lambda` instance created, it will help to fully define the closure in the lambda expression - so rather than `Lambda.Groovy(""it.get().value('name'))`, prefer `Lambda.Groovy(""x -> x.get().value('name'))`. === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. Gremlin scripts are sent to the server from a `IGremlinClient` instance. A `IGremlinClient` is created as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=submittingScripts] ---- If the remote system has authentication and SSL enabled, then the `GremlinServer` object can be configured as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsTests.cs[tags=submittingScriptsWithAuthentication] ---- It is also possible to initialize the `Client` to use <>: [source,csharp] ---- var gremlinServer = new GremlinServer(""localhost"", 8182); var client = new GremlinClient(gremlinServer, sessionId: Guid.NewGuid().ToString())) ---- [[gremlin-net-dsl]] === Domain Specific Languages Developing a <> (DSL) for .Net is most easily implemented using link:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods[Extension Methods] as they don't require direct extension of classes in the TinkerPop hierarchy. Extension Method classes simply need to be constructed for the `GraphTraversal` and the `GraphTraversalSource`. Unfortunately, anonymous traversals (spawned from `+__+`) can't use the Extension Method approach as they do not work for static classes and static classes can't be extended. The only option is to re-implement the methods of `+__+` as a wrapper in the anonymous traversal for the DSL or to simply create a static class for the DSL and use the two anonymous traversals creators independently. The following example uses the latter approach as it saves a lot of boilerplate code with the minor annoyance of having a second static class to deal with when writing traversals rather than just calling `+__+` for everything. [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDsl.cs[tags=dsl] ---- Note the creation of `__Social` as the Social DSL's ""extension"" to the available ways in which to spawn anonymous traversals. The use of the double underscore prefix in the name is just a convention to consider using and is not a requirement. To use the DSL, bring it into scope with the `using` directive: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDslTests.cs[tags=dslUsing] ---- and then it can be called from the application as follows: [source,csharp] ---- include::../../../gremlin-dotnet/test/Gremlin.Net.IntegrationTest/Docs/Reference/GremlinVariantsDslTests.cs[tags=dslExamples] ---- [[gremlin-dotnet-differences]] === Differences Gremlin allows for `Map` instances to include `null` keys, but `null` keys in C# `Dictionary` instances are not allowed. It is therefore necessary to rewrite a traversal such as: [source,javascript] ---- g.V().groupCount().by('age') ---- where ""age"" is not a valid key for all vertices in a way that will remove the need for a `null` to be returned. [source,javascript] ---- g.V().has('age').groupCount().by('age') g.V().hasLabel('person').groupCount().by('age') ---- Either of the above two options accomplishes the desired goal as both prevent `groupCount()` from having to process the possibility of `null`. anchor:gremlin-dotnet-template[] [[dotnet-application-examples]] === Application Examples This link:https://docs.microsoft.com/dotnet/core/tools/custom-templates[dotnet template] helps getting started with <>. It creates a new C# console project that shows how to connect to a <> with Gremlin.Net. You can install the template with the dotnet CLI tool: [source,shell] dotnet new -i Gremlin.Net.Template After the template is installed, a new project based on this template can be installed: [source,shell] dotnet new gremlin Specify the output directory for the new project which will then also be used as the name of the created project: [source,shell] dotnet new gremlin -o MyFirstGremlinProject [[gremlin-javascript]] == Gremlin-JavaScript image:gremlin-js.png[width=130,float=right] Apache TinkerPop's Gremlin-JavaScript implements Gremlin within the JavaScript language. It targets Node.js runtime and can be used on different operating systems on any Node.js 6 or above. Since the JavaScript naming conventions are very similar to that of Java, it should be very easy to switch between Gremlin-Java and Gremlin-JavaScript. [source,bash] npm install gremlin === Connecting The pattern for connecting is described in <> and it basically distills down to creating a `GraphTraversalSource`. A `GraphTraversalSource` is created from the `AnonymousTraversalSource.traversal()` method where the ""g"" provided to the `DriverRemoteConnection` corresponds to the name of a `GraphTraversalSource` on the remote end. [source,javascript] ---- const g = traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin')); ---- Gremlin-JavaScript supports plain text SASL authentication, you can set it on the connection options. [source,javascript] ---- const authenticator = new gremlin.driver.auth.PlainTextSaslAuthenticator('myuser', 'mypassword'); const g = traversal().withRemote(new DriverRemoteConnection('ws://localhost:8182/gremlin', { authenticator }); ---- Given that I/O operations in Node.js are asynchronous by default, <> return a `Promise`: * `Traversal.toList()`: Returns a `Promise` with an `Array` as result value. * `Traversal.next()`: Returns a `Promise` with a `{ value, done }` tuple as result value, according to the link:https://github.com/tc39/proposal-async-iteration[async iterator proposal]. * `Traversal.iterate()`: Returns a `Promise` without a value. For example: [source,javascript] ---- g.V().hasLabel('person').values('name').toList() .then(names => console.log(names)); ---- When using `async` functions it is possible to `await` the promises: [source,javascript] ---- const names = await g.V().hasLabel('person').values('name').toList(); console.log(names); ---- === Common Imports There are a number of classes, functions and tokens that are typically used with Gremlin. The following imports provide most of the typical functionality required to use Gremlin: [source,javascript] ---- const gremlin = require('gremlin'); const traversal = gremlin.process.AnonymousTraversalSource.traversal; const __ = gremlin.process.statics; const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection; const column = gremlin.process.column const direction = gremlin.process.direction const p = gremlin.process.P const textp = gremlin.process.TextP const pick = gremlin.process.pick const pop = gremlin.process.pop const order = gremlin.process.order const scope = gremlin.process.scope const t = gremlin.process.t ---- === Submitting Scripts WARNING: TinkerPop does not recommend submitting script-based requests and generally continues to support this feature for legacy reasons and corner use cases which are still not completely addressed by the Gremlin language. Please consider using bytecode-based requests instead when possible. It is possible to submit parametrized Gremlin scripts to the server as strings, using the `Client` class: [source,javascript] ---- const gremlin = require('gremlin'); const client = new gremlin.driver.Client('ws://localhost:8182/gremlin', { traversalSource: 'g' }); const result1 = await client.submit('g.V(vid)', { vid: 1 }); const vertex = result1.first(); const result2 = await client.submit('g.V().hasLabel(label).tail(n)', { label: 'person', n: 3 }); // ResultSet is an iterable for (const vertex of result2) { console.log(vertex.id); } ---- It is also possible to initialize the `Client` to use <>: [source,javascript] ---- const client = new gremlin.driver.Client('ws://localhost:8182/gremlin', { traversalSource: 'g', 'session': 'unique-string-id' }); ---- With this configuration, the state of variables within scripts are preserved between requests. [[gremlin-javascript-dsl]] === Domain Specific Languages Developing Gremlin DSLs in JavaScript largely requires extension of existing core classes with use of standalone functions for anonymous traversal spawning. The pattern is demonstrated in the following example: [source,javascript] ---- class SocialTraversal extends GraphTraversal { constructor(graph, traversalStrategies, bytecode) { super(graph, traversalStrategies, bytecode); } aged(age) { return this.has('person', 'age', age); } } class SocialTraversalSource extends GraphTraversalSource { constructor(graph, traversalStrategies, bytecode) { super(graph, traversalStrategies, bytecode, SocialTraversalSource, SocialTraversal); } person(name) { return this.V().has('person', 'name', name); } } function anonymous() { return new SocialTraversal(null, null, new Bytecode()); } function aged(age) { return anonymous().aged(age); } ---- `SocialTraversal` extends the core `GraphTraversal` class and has a three argument constructor which is immediately proxied to the `GraphTraversal` constructor. New DSL steps are then added to this class using available steps to construct the underlying traversal to execute as demonstrated in the `aged()` step. The `SocialTraversal` is spawned from a `SocialTraversalSource` which is extended from `GraphTraversalSource`. Steps added here are meant to be start steps. In the above case, the `person()` start step find a ""person"" vertex to begin the traversal from. Typically, steps that are made available on a `GraphTraversal` (i.e. SocialTraversal in this example) should also be made available as spawns for anonymous traversals. The recommendation is that these steps be exposed in the module as standalone functions. In the example above, the standalone `aged()` step creates an anonymous traversal through an `anonymous()` utility function. The method for creating these standalone functions can be handled in other ways if desired. To use the DSL, simply initialize the `g` as follows: [source,javascript] ---- const g = traversal(SocialTraversalSource).withRemote(connection); g.person('marko').aged(29).values('name').toList(). then(names => console.log(names)); ---- [[gremlin-javascript-differences]] === Differences In situations where Javascript reserved words and global functions overlap with standard Gremlin steps and tokens, those bits of conflicting Gremlin get an underscore appended as a suffix: *Steps* - <>, <>, <> Gremlin allows for `Map` instances to include `null` keys, but `null` keys in Javascript have some interesting behavior as in: [source,text] ---- > var a = { null: 'something', 'b': 'else' }; > JSON.stringify(a) '{""null"":""something"",""b"":""else""}' > JSON.parse(JSON.stringify(a)) { null: 'something', b: 'else' } > a[null] 'something' > a['null'] 'something' ---- This behavior needs to be considered when using Gremlin to return such results. A typical situation where this might happen is with `group()` or `groupCount()` as in: [source,javascript] ---- g.V().groupCount().by('age') ---- where ""age"" is not a valid key for all vertices. In these cases, it will return `null` for that key and group on that. It may bet better in Javascript to filter away those vertices to avoid the return of `null` in the returned `Map`: [source,javascript] ---- g.V().has('age').groupCount().by('age') g.V().hasLabel('person').groupCount().by('age') ---- Either of the above two options accomplishes the desired goal as both prevent `groupCount()` from having to process the possibility of `null`.",16148,True,2742.610088285307,median "INTERFACE zif_abapgit_definitions PUBLIC . TYPES: ty_type TYPE c LENGTH 6 . TYPES: ty_bitbyte TYPE c LENGTH 8 . TYPES: ty_sha1 TYPE c LENGTH 40 . TYPES: ty_adler32 TYPE x LENGTH 4 . TYPES: BEGIN OF ty_file_signature, path TYPE string, filename TYPE string, sha1 TYPE ty_sha1, END OF ty_file_signature . TYPES: ty_file_signatures_tt TYPE STANDARD TABLE OF ty_file_signature WITH DEFAULT KEY . TYPES: ty_file_signatures_ts TYPE SORTED TABLE OF ty_file_signature WITH UNIQUE KEY path filename . TYPES: BEGIN OF ty_file. INCLUDE TYPE ty_file_signature. TYPES: data TYPE xstring, END OF ty_file . TYPES: ty_files_tt TYPE STANDARD TABLE OF ty_file WITH DEFAULT KEY . TYPES: ty_string_tt TYPE STANDARD TABLE OF string WITH DEFAULT KEY . TYPES: ty_repo_ref_tt TYPE STANDARD TABLE OF REF TO zcl_abapgit_repo WITH DEFAULT KEY . TYPES ty_git_branch_type TYPE c LENGTH 2 . TYPES: BEGIN OF ty_git_branch, sha1 TYPE ty_sha1, name TYPE string, type TYPE ty_git_branch_type, is_head TYPE abap_bool, display_name TYPE string, END OF ty_git_branch . TYPES: ty_git_branch_list_tt TYPE STANDARD TABLE OF ty_git_branch WITH DEFAULT KEY . TYPES: BEGIN OF ty_git_tag, sha1 TYPE ty_sha1, object TYPE ty_sha1, name TYPE string, type TYPE ty_git_branch_type, display_name TYPE string, tagger_name TYPE string, tagger_email TYPE string, message TYPE string, body TYPE string, END OF ty_git_tag . TYPES: ty_git_tag_list_tt TYPE STANDARD TABLE OF ty_git_tag WITH DEFAULT KEY . TYPES: BEGIN OF ty_hotkey, ui_component TYPE string, action TYPE string, hotkey TYPE string, END OF ty_hotkey . TYPES: tty_hotkey TYPE STANDARD TABLE OF ty_hotkey WITH NON-UNIQUE DEFAULT KEY WITH NON-UNIQUE SORTED KEY action COMPONENTS ui_component action. TYPES: BEGIN OF ty_git_user, name TYPE string, email TYPE string, END OF ty_git_user . TYPES: BEGIN OF ty_comment, committer TYPE ty_git_user, author TYPE ty_git_user, comment TYPE string, END OF ty_comment . TYPES: BEGIN OF ty_item, obj_type TYPE tadir-object, obj_name TYPE tadir-obj_name, devclass TYPE devclass, inactive TYPE abap_bool, END OF ty_item . TYPES: ty_items_tt TYPE STANDARD TABLE OF ty_item WITH DEFAULT KEY . TYPES: ty_items_ts TYPE SORTED TABLE OF ty_item WITH UNIQUE KEY obj_type obj_name . TYPES: BEGIN OF ty_file_item, file TYPE ty_file, item TYPE ty_item, END OF ty_file_item . TYPES: ty_files_item_tt TYPE STANDARD TABLE OF ty_file_item WITH DEFAULT KEY . TYPES: ty_yes_no TYPE c LENGTH 1, ty_yes_no_partial TYPE c LENGTH 1. TYPES: BEGIN OF ty_overwrite. INCLUDE TYPE ty_item. TYPES: decision TYPE ty_yes_no, END OF ty_overwrite . TYPES: ty_overwrite_tt TYPE STANDARD TABLE OF ty_overwrite WITH DEFAULT KEY WITH UNIQUE HASHED KEY object_type_and_name COMPONENTS obj_type obj_name . TYPES: BEGIN OF ty_requirements, met TYPE ty_yes_no, decision TYPE ty_yes_no, END OF ty_requirements . TYPES: BEGIN OF ty_dependencies, met TYPE ty_yes_no, END OF ty_dependencies . TYPES: BEGIN OF ty_transport_type, request TYPE trfunction, task TYPE trfunction, END OF ty_transport_type . TYPES: BEGIN OF ty_transport, required TYPE abap_bool, transport TYPE trkorr, type TYPE ty_transport_type, END OF ty_transport . TYPES: BEGIN OF ty_deserialize_checks, overwrite TYPE ty_overwrite_tt, warning_package TYPE ty_overwrite_tt, requirements TYPE ty_requirements, dependencies TYPE ty_dependencies, transport TYPE ty_transport, END OF ty_deserialize_checks . TYPES: BEGIN OF ty_delete_checks, transport TYPE ty_transport, END OF ty_delete_checks . TYPES: BEGIN OF ty_metadata, class TYPE string, version TYPE string, late_deser TYPE abap_bool, "" refactor: can be removed later. replaced by steps delete_tadir TYPE abap_bool, ddic TYPE abap_bool, END OF ty_metadata . TYPES: BEGIN OF ty_repo_file, path TYPE string, filename TYPE string, is_changed TYPE abap_bool, rstate TYPE c LENGTH 1, lstate TYPE c LENGTH 1, END OF ty_repo_file . TYPES: tt_repo_files TYPE STANDARD TABLE OF ty_repo_file WITH DEFAULT KEY . TYPES: ty_chmod TYPE c LENGTH 6 . TYPES: BEGIN OF ty_object, sha1 TYPE ty_sha1, type TYPE ty_type, data TYPE xstring, adler32 TYPE ty_adler32, index TYPE i, END OF ty_object . TYPES: ty_objects_tt TYPE STANDARD TABLE OF ty_object WITH DEFAULT KEY WITH NON-UNIQUE SORTED KEY sha COMPONENTS sha1 WITH NON-UNIQUE SORTED KEY type COMPONENTS type sha1 . TYPES: BEGIN OF ty_tadir, pgmid TYPE tadir-pgmid, object TYPE tadir-object, obj_name TYPE tadir-obj_name, devclass TYPE tadir-devclass, korrnum TYPE tadir-korrnum, delflag TYPE tadir-delflag, genflag TYPE tadir-genflag, path TYPE string, END OF ty_tadir . TYPES: ty_tadir_tt TYPE STANDARD TABLE OF ty_tadir WITH DEFAULT KEY . TYPES: BEGIN OF ty_result, obj_type TYPE tadir-object, obj_name TYPE tadir-obj_name, inactive TYPE abap_bool, path TYPE string, filename TYPE string, package TYPE devclass, match TYPE abap_bool, lstate TYPE c LENGTH 1, rstate TYPE c LENGTH 1, END OF ty_result . TYPES: ty_results_tt TYPE STANDARD TABLE OF ty_result WITH DEFAULT KEY . TYPES: ty_results_ts_path TYPE HASHED TABLE OF ty_result WITH UNIQUE KEY path filename . TYPES: BEGIN OF ty_stage_files, local TYPE ty_files_item_tt, remote TYPE ty_files_tt, status TYPE ty_results_ts_path, END OF ty_stage_files . TYPES: ty_sval_tt TYPE STANDARD TABLE OF sval WITH DEFAULT KEY . TYPES: ty_seocompotx_tt TYPE STANDARD TABLE OF seocompotx WITH DEFAULT KEY . TYPES: BEGIN OF ty_tpool. INCLUDE TYPE textpool. TYPES: split TYPE c LENGTH 8. TYPES: END OF ty_tpool . TYPES: ty_tpool_tt TYPE STANDARD TABLE OF ty_tpool WITH DEFAULT KEY . TYPES: BEGIN OF ty_sotr, header TYPE sotr_head, entries TYPE sotr_text_tt, END OF ty_sotr . TYPES: ty_sotr_tt TYPE STANDARD TABLE OF ty_sotr WITH DEFAULT KEY . TYPES: BEGIN OF ty_obj_attribute, cmpname TYPE seocmpname, attkeyfld TYPE seokeyfld, attbusobj TYPE seobusobj, END OF ty_obj_attribute . TYPES: ty_obj_attribute_tt TYPE STANDARD TABLE OF ty_obj_attribute WITH DEFAULT KEY WITH NON-UNIQUE SORTED KEY cmpname COMPONENTS cmpname . TYPES: BEGIN OF ty_transport_to_branch, branch_name TYPE string, commit_text TYPE string, END OF ty_transport_to_branch . TYPES: BEGIN OF ty_create, name TYPE string, parent TYPE string, END OF ty_create . TYPES: BEGIN OF ty_commit, sha1 TYPE ty_sha1, parent1 TYPE ty_sha1, parent2 TYPE ty_sha1, author TYPE string, email TYPE string, time TYPE string, message TYPE string, body TYPE STANDARD TABLE OF string WITH DEFAULT KEY, branch TYPE string, merge TYPE string, tags TYPE STANDARD TABLE OF string WITH DEFAULT KEY, create TYPE STANDARD TABLE OF ty_create WITH DEFAULT KEY, compressed TYPE abap_bool, END OF ty_commit . TYPES: ty_commit_tt TYPE STANDARD TABLE OF ty_commit WITH DEFAULT KEY . TYPES: BEGIN OF ty_diff, patch_flag TYPE abap_bool, new_num TYPE c LENGTH 6, new TYPE string, result TYPE c LENGTH 1, old_num TYPE c LENGTH 6, old TYPE string, short TYPE abap_bool, beacon TYPE i, END OF ty_diff . TYPES: ty_diffs_tt TYPE STANDARD TABLE OF ty_diff WITH DEFAULT KEY . TYPES: BEGIN OF ty_count, insert TYPE i, delete TYPE i, update TYPE i, END OF ty_count . TYPES: BEGIN OF ty_expanded, path TYPE string, name TYPE string, sha1 TYPE ty_sha1, chmod TYPE ty_chmod, END OF ty_expanded . TYPES: ty_expanded_tt TYPE STANDARD TABLE OF ty_expanded WITH DEFAULT KEY . TYPES: BEGIN OF ty_ancestor, commit TYPE ty_sha1, tree TYPE ty_sha1, time TYPE string, body TYPE string, END OF ty_ancestor . TYPES: BEGIN OF ty_merge, repo TYPE REF TO zcl_abapgit_repo_online, source TYPE ty_git_branch, target TYPE ty_git_branch, common TYPE ty_ancestor, stree TYPE ty_expanded_tt, ttree TYPE ty_expanded_tt, ctree TYPE ty_expanded_tt, result TYPE ty_expanded_tt, stage TYPE REF TO zcl_abapgit_stage, conflict TYPE string, END OF ty_merge . TYPES: BEGIN OF ty_merge_conflict, path TYPE string, filename TYPE string, source_sha1 TYPE ty_sha1, source_data TYPE xstring, target_sha1 TYPE ty_sha1, target_data TYPE xstring, result_sha1 TYPE ty_sha1, result_data TYPE xstring, END OF ty_merge_conflict . TYPES: tt_merge_conflict TYPE STANDARD TABLE OF ty_merge_conflict WITH DEFAULT KEY . TYPES: BEGIN OF ty_repo_item, obj_type TYPE tadir-object, obj_name TYPE tadir-obj_name, inactive TYPE abap_bool, sortkey TYPE i, path TYPE string, is_dir TYPE abap_bool, changes TYPE i, lstate TYPE c LENGTH 1, rstate TYPE c LENGTH 1, files TYPE tt_repo_files, END OF ty_repo_item . TYPES: tt_repo_items TYPE STANDARD TABLE OF ty_repo_item WITH DEFAULT KEY . TYPES: BEGIN OF ty_s_user_settings, max_lines TYPE i, adt_jump_enabled TYPE abap_bool, show_default_repo TYPE abap_bool, link_hints_enabled TYPE abap_bool, link_hint_key TYPE c LENGTH 1, hotkeys TYPE tty_hotkey, parallel_proc_disabled TYPE abap_bool, icon_scaling TYPE c LENGTH 1, ui_theme TYPE string, hide_sapgui_hint TYPE abap_bool, END OF ty_s_user_settings . TYPES: tty_dokil TYPE STANDARD TABLE OF dokil WITH NON-UNIQUE DEFAULT KEY . TYPES: tty_lines TYPE STANDARD TABLE OF i WITH NON-UNIQUE DEFAULT KEY . TYPES: BEGIN OF ty_col_spec, tech_name TYPE string, display_name TYPE string, css_class TYPE string, add_tz TYPE abap_bool, title TYPE string, END OF ty_col_spec, tty_col_spec TYPE STANDARD TABLE OF ty_col_spec WITH NON-UNIQUE KEY tech_name. TYPES: ty_proxy_bypass_url TYPE c LENGTH 255, ty_range_proxy_bypass_url TYPE RANGE OF ty_proxy_bypass_url. TYPES: BEGIN OF ty_version, major TYPE i, minor TYPE i, patch TYPE i, prerelase TYPE string, prerelase_patch TYPE i, END OF ty_version. TYPES: BEGIN OF ty_alv_column, name TYPE string, text TYPE string, length TYPE lvc_outlen, END OF ty_alv_column, ty_alv_column_tt TYPE TABLE OF ty_alv_column WITH DEFAULT KEY. CONSTANTS: BEGIN OF c_git_branch_type, branch TYPE ty_git_branch_type VALUE 'HD', lightweight_tag TYPE ty_git_branch_type VALUE 'TG', annotated_tag TYPE ty_git_branch_type VALUE 'AT', other TYPE ty_git_branch_type VALUE 'ZZ', END OF c_git_branch_type . CONSTANTS c_head_name TYPE string VALUE 'HEAD' ##NO_TEXT. CONSTANTS: BEGIN OF c_diff, insert TYPE c LENGTH 1 VALUE 'I', delete TYPE c LENGTH 1 VALUE 'D', update TYPE c LENGTH 1 VALUE 'U', END OF c_diff . CONSTANTS: BEGIN OF c_type, commit TYPE ty_type VALUE 'commit', ""#EC NOTEXT tree TYPE ty_type VALUE 'tree', ""#EC NOTEXT ref_d TYPE ty_type VALUE 'ref_d', ""#EC NOTEXT tag TYPE ty_type VALUE 'tag', ""#EC NOTEXT blob TYPE ty_type VALUE 'blob', ""#EC NOTEXT END OF c_type . CONSTANTS: BEGIN OF c_state, "" https://git-scm.com/docs/git-status unchanged TYPE c LENGTH 1 VALUE '', added TYPE c LENGTH 1 VALUE 'A', modified TYPE c LENGTH 1 VALUE 'M', deleted TYPE c LENGTH 1 VALUE 'D', ""For future use mixed TYPE c LENGTH 1 VALUE '*', END OF c_state . CONSTANTS: BEGIN OF c_chmod, file TYPE ty_chmod VALUE '100644', executable TYPE ty_chmod VALUE '100755', dir TYPE ty_chmod VALUE '40000 ', END OF c_chmod . CONSTANTS c_crlf TYPE abap_cr_lf VALUE cl_abap_char_utilities=>cr_lf ##NO_TEXT. CONSTANTS c_newline TYPE abap_char1 VALUE cl_abap_char_utilities=>newline ##NO_TEXT. CONSTANTS c_english TYPE spras VALUE 'E' ##NO_TEXT. CONSTANTS c_root_dir TYPE string VALUE '/' ##NO_TEXT. CONSTANTS c_dot_abapgit TYPE string VALUE '.abapgit.xml' ##NO_TEXT. CONSTANTS c_author_regex TYPE string VALUE '^(.+) <(.*)> (\\d{10})\\s?.\\d{4}$' ##NO_TEXT. CONSTANTS: BEGIN OF c_action, repo_refresh TYPE string VALUE 'repo_refresh', repo_remove TYPE string VALUE 'repo_remove', repo_settings TYPE string VALUE 'repo_settings', repo_purge TYPE string VALUE 'repo_purge', repo_newonline TYPE string VALUE 'repo_newonline', repo_newoffline TYPE string VALUE 'repo_newoffline', repo_add_all_obj_to_trans_req TYPE string VALUE 'repo_add_all_obj_to_trans_req', repo_remote_attach TYPE string VALUE 'repo_remote_attach', repo_remote_detach TYPE string VALUE 'repo_remote_detach', repo_remote_change TYPE string VALUE 'repo_remote_change', repo_refresh_checksums TYPE string VALUE 'repo_refresh_checksums', repo_toggle_fav TYPE string VALUE 'repo_toggle_fav', repo_transport_to_branch TYPE string VALUE 'repo_transport_to_branch', repo_syntax_check TYPE string VALUE 'repo_syntax_check', repo_code_inspector TYPE string VALUE 'repo_code_inspector', repo_open_in_master_lang TYPE string VALUE 'repo_open_in_master_lang', repo_log TYPE string VALUE 'repo_log', abapgit_home TYPE string VALUE 'abapgit_home', abapgit_install TYPE string VALUE 'abapgit_install', zip_import TYPE string VALUE 'zip_import', zip_export TYPE string VALUE 'zip_export', zip_package TYPE string VALUE 'zip_package', zip_transport TYPE string VALUE 'zip_transport', zip_object TYPE string VALUE 'zip_object', git_pull TYPE string VALUE 'git_pull', git_reset TYPE string VALUE 'git_reset', git_branch_create TYPE string VALUE 'git_branch_create', git_branch_switch TYPE string VALUE 'git_branch_switch', git_branch_delete TYPE string VALUE 'git_branch_delete', git_tag_create TYPE string VALUE 'git_tag_create', git_tag_delete TYPE string VALUE 'git_tag_delete', git_tag_switch TYPE string VALUE 'git_tag_switch', git_commit TYPE string VALUE 'git_commit', db_display TYPE string VALUE 'db_display', db_edit TYPE string VALUE 'db_edit', bg_update TYPE string VALUE 'bg_update', go_explore TYPE string VALUE 'go_explore', go_repo_overview TYPE string VALUE 'go_repo_overview', go_db TYPE string VALUE 'go_db', go_background TYPE string VALUE 'go_background', go_background_run TYPE string VALUE 'go_background_run', go_diff TYPE string VALUE 'go_diff', go_stage TYPE string VALUE 'go_stage', go_commit TYPE string VALUE 'go_commit', go_branch_overview TYPE string VALUE 'go_branch_overview', go_tag_overview TYPE string VALUE 'go_tag_overview', go_debuginfo TYPE string VALUE 'go_debuginfo', go_settings TYPE string VALUE 'go_settings', go_tutorial TYPE string VALUE 'go_tutorial', go_patch TYPE string VALUE 'go_patch', jump TYPE string VALUE 'jump', jump_transport TYPE string VALUE 'jump_transport', url TYPE string VALUE 'url', goto_source TYPE string VALUE 'goto_source', show_callstack TYPE string VALUE 'show_callstack', change_order_by TYPE string VALUE 'change_order_by', goto_message TYPE string VALUE 'goto_message', direction TYPE string VALUE 'direction', END OF c_action . CONSTANTS c_tag_prefix TYPE string VALUE 'refs/tags/' ##NO_TEXT. CONSTANTS c_spagpa_param_repo_key TYPE c LENGTH 20 VALUE 'REPO_KEY' ##NO_TEXT. CONSTANTS c_spagpa_param_package TYPE c LENGTH 20 VALUE 'PACKAGE' ##NO_TEXT. CONSTANTS gc_yes TYPE ty_yes_no VALUE 'Y'. CONSTANTS gc_no TYPE ty_yes_no VALUE 'N'. CONSTANTS gc_partial TYPE ty_yes_no_partial VALUE 'P'. TYPES: ty_method TYPE c LENGTH 1 . TYPES: BEGIN OF ty_stage, file TYPE ty_file, method TYPE ty_method, status TYPE ty_result, END OF ty_stage . TYPES: ty_stage_tt TYPE SORTED TABLE OF ty_stage WITH UNIQUE KEY file-path file-filename . CONSTANTS: BEGIN OF c_method, add TYPE ty_method VALUE 'A', rm TYPE ty_method VALUE 'R', ignore TYPE ty_method VALUE 'I', skip TYPE ty_method VALUE '?', END OF c_method . ENDINTERFACE. ",4364,False,1190.3787616891148,median "class ZCL_ZRULERUNNER_ODATA_DPC definition public inheriting from /IWBEP/CL_MGW_PUSH_ABS_DATA abstract create public . public section. interfaces /IWBEP/IF_SB_DPC_COMM_SERVICES . interfaces /IWBEP/IF_SB_GEN_DPC_INJECTION . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_ENTITYSET redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_ENTITY redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~UPDATE_ENTITY redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_ENTITY redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~DELETE_ENTITY redefinition . protected section. data mo_injection type ref to /IWBEP/IF_SB_GEN_DPC_INJECTION . methods RULERUNNERKEYVAL_CREATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_C optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_ZRULERUNNER_ODATA_MPC=>TS_RULERUNNERKEYVALUE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods RULERUNNERKEYVAL_DELETE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_D optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods RULERUNNERKEYVAL_GET_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_REQUEST_OBJECT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH exporting !ER_ENTITY type ZCL_ZRULERUNNER_ODATA_MPC=>TS_RULERUNNERKEYVALUE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_ENTITY_CNTXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods RULERUNNERKEYVAL_GET_ENTITYSET importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_FILTER_SELECT_OPTIONS type /IWBEP/T_MGW_SELECT_OPTION !IS_PAGING type /IWBEP/S_MGW_PAGING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IT_ORDER type /IWBEP/T_MGW_SORTING_ORDER !IV_FILTER_STRING type STRING !IV_SEARCH_STRING type STRING !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITYSET optional exporting !ET_ENTITYSET type ZCL_ZRULERUNNER_ODATA_MPC=>TT_RULERUNNERKEYVALUE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_CONTEXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods RULERUNNERKEYVAL_UPDATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_U optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_ZRULERUNNER_ODATA_MPC=>TS_RULERUNNERKEYVALUE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods CHECK_SUBSCRIPTION_AUTHORITY redefinition . private section. ENDCLASS. CLASS ZCL_ZRULERUNNER_ODATA_DPC IMPLEMENTATION. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_ENTITY. *&----------------------------------------------------------------------------------------------* *& Include /IWBEP/DPC_TEMP_CRT_ENTITY_BASE *&* This class has been generated on 21.12.2018 13:30:48 in client 001 *&* *&* WARNING--> NEVER MODIFY THIS CLASS <--WARNING *&* If you want to change the DPC implementation, use the *&* generated methods inside the DPC provider subclass - ZCL_ZRULERUNNER_ODATA_DPC_EXT *&-----------------------------------------------------------------------------------------------* DATA rulerunnerkeyval_create_entity TYPE zcl_zrulerunner_odata_mpc=>ts_rulerunnerkeyvalue. DATA lv_entityset_name TYPE string. lv_entityset_name = io_tech_request_context->get_entity_set_name( ). CASE lv_entityset_name. *-------------------------------------------------------------------------* * EntitySet - rulerunnerKeyValueSet *-------------------------------------------------------------------------* WHEN 'rulerunnerKeyValueSet'. * Call the entity set generated method rulerunnerkeyval_create_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = rulerunnerkeyval_create_entity ). * Send specific entity data to the caller interfaces copy_data_to_ref( EXPORTING is_data = rulerunnerkeyval_create_entity CHANGING cr_data = er_entity ). when others. super->/iwbep/if_mgw_appl_srv_runtime~create_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path IMPORTING er_entity = er_entity ). ENDCASE. endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~DELETE_ENTITY. *&----------------------------------------------------------------------------------------------* *& Include /IWBEP/DPC_TEMP_DEL_ENTITY_BASE *&* This class has been generated on 21.12.2018 13:30:48 in client 001 *&* *&* WARNING--> NEVER MODIFY THIS CLASS <--WARNING *&* If you want to change the DPC implementation, use the *&* generated methods inside the DPC provider subclass - ZCL_ZRULERUNNER_ODATA_DPC_EXT *&-----------------------------------------------------------------------------------------------* DATA lv_entityset_name TYPE string. lv_entityset_name = io_tech_request_context->get_entity_set_name( ). CASE lv_entityset_name. *-------------------------------------------------------------------------* * EntitySet - rulerunnerKeyValueSet *-------------------------------------------------------------------------* when 'rulerunnerKeyValueSet'. * Call the entity set generated method rulerunnerkeyval_delete_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context ). when others. super->/iwbep/if_mgw_appl_srv_runtime~delete_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path ). ENDCASE. endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_ENTITY. *&-----------------------------------------------------------------------------------------------* *& Include /IWBEP/DPC_TEMP_GETENTITY_BASE *&* This class has been generated on 21.12.2018 13:30:48 in client 001 *&* *&* WARNING--> NEVER MODIFY THIS CLASS <--WARNING *&* If you want to change the DPC implementation, use the *&* generated methods inside the DPC provider subclass - ZCL_ZRULERUNNER_ODATA_DPC_EXT *&-----------------------------------------------------------------------------------------------* DATA rulerunnerkeyval_get_entity TYPE zcl_zrulerunner_odata_mpc=>ts_rulerunnerkeyvalue. DATA lv_entityset_name TYPE string. DATA lr_entity TYPE REF TO data. lv_entityset_name = io_tech_request_context->get_entity_set_name( ). CASE lv_entityset_name. *-------------------------------------------------------------------------* * EntitySet - rulerunnerKeyValueSet *-------------------------------------------------------------------------* WHEN 'rulerunnerKeyValueSet'. * Call the entity set generated method rulerunnerkeyval_get_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = rulerunnerkeyval_get_entity es_response_context = es_response_context ). IF rulerunnerkeyval_get_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = rulerunnerkeyval_get_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. WHEN OTHERS. super->/iwbep/if_mgw_appl_srv_runtime~get_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path IMPORTING er_entity = er_entity ). ENDCASE. endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_ENTITYSET. *&----------------------------------------------------------------------------------------------* *& Include /IWBEP/DPC_TMP_ENTITYSET_BASE *&* This class has been generated on 21.12.2018 13:30:48 in client 001 *&* *&* WARNING--> NEVER MODIFY THIS CLASS <--WARNING *&* If you want to change the DPC implementation, use the *&* generated methods inside the DPC provider subclass - ZCL_ZRULERUNNER_ODATA_DPC_EXT *&-----------------------------------------------------------------------------------------------* DATA rulerunnerkeyval_get_entityset TYPE zcl_zrulerunner_odata_mpc=>tt_rulerunnerkeyvalue. DATA lv_entityset_name TYPE string. lv_entityset_name = io_tech_request_context->get_entity_set_name( ). CASE lv_entityset_name. *-------------------------------------------------------------------------* * EntitySet - rulerunnerKeyValueSet *-------------------------------------------------------------------------* WHEN 'rulerunnerKeyValueSet'. * Call the entity set generated method rulerunnerkeyval_get_entityset( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_filter_select_options = it_filter_select_options it_order = it_order is_paging = is_paging it_navigation_path = it_navigation_path it_key_tab = it_key_tab iv_filter_string = iv_filter_string iv_search_string = iv_search_string io_tech_request_context = io_tech_request_context IMPORTING et_entityset = rulerunnerkeyval_get_entityset es_response_context = es_response_context ). * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = rulerunnerkeyval_get_entityset CHANGING cr_data = er_entityset ). WHEN OTHERS. super->/iwbep/if_mgw_appl_srv_runtime~get_entityset( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_filter_select_options = it_filter_select_options it_order = it_order is_paging = is_paging it_navigation_path = it_navigation_path it_key_tab = it_key_tab iv_filter_string = iv_filter_string iv_search_string = iv_search_string io_tech_request_context = io_tech_request_context IMPORTING er_entityset = er_entityset ). ENDCASE. endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~UPDATE_ENTITY. *&----------------------------------------------------------------------------------------------* *& Include /IWBEP/DPC_TEMP_UPD_ENTITY_BASE *&* This class has been generated on 21.12.2018 13:30:48 in client 001 *&* *&* WARNING--> NEVER MODIFY THIS CLASS <--WARNING *&* If you want to change the DPC implementation, use the *&* generated methods inside the DPC provider subclass - ZCL_ZRULERUNNER_ODATA_DPC_EXT *&-----------------------------------------------------------------------------------------------* DATA rulerunnerkeyval_update_entity TYPE zcl_zrulerunner_odata_mpc=>ts_rulerunnerkeyvalue. DATA lv_entityset_name TYPE string. DATA lr_entity TYPE REF TO data. lv_entityset_name = io_tech_request_context->get_entity_set_name( ). CASE lv_entityset_name. *-------------------------------------------------------------------------* * EntitySet - rulerunnerKeyValueSet *-------------------------------------------------------------------------* WHEN 'rulerunnerKeyValueSet'. * Call the entity set generated method rulerunnerkeyval_update_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = rulerunnerkeyval_update_entity ). IF rulerunnerkeyval_update_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = rulerunnerkeyval_update_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. WHEN OTHERS. super->/iwbep/if_mgw_appl_srv_runtime~update_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path IMPORTING er_entity = er_entity ). ENDCASE. endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~COMMIT_WORK. * Call RFC commit work functionality DATA lt_message TYPE bapiret2. DATA lv_message_text TYPE BAPI_MSG. DATA lo_logger TYPE REF TO /iwbep/cl_cos_logger. DATA lv_subrc TYPE syst-subrc. lo_logger = /iwbep/if_mgw_conv_srv_runtime~get_logger( ). IF iv_rfc_dest IS INITIAL OR iv_rfc_dest EQ 'NONE'. CALL FUNCTION 'BAPI_TRANSACTION_COMMIT' EXPORTING wait = abap_true IMPORTING return = lt_message. ELSE. CALL FUNCTION 'BAPI_TRANSACTION_COMMIT' DESTINATION iv_rfc_dest EXPORTING wait = abap_true IMPORTING return = lt_message EXCEPTIONS communication_failure = 1000 MESSAGE lv_message_text system_failure = 1001 MESSAGE lv_message_text OTHERS = 1002. IF sy-subrc <> 0. lv_subrc = sy-subrc. /iwbep/cl_sb_gen_dpc_rt_util=>rfc_exception_handling( EXPORTING iv_subrc = lv_subrc iv_exp_message_text = lv_message_text io_logger = lo_logger ). EXIT. ENDIF. ENDIF. endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~GET_GENERATION_STRATEGY. * Get generation strategy rv_generation_strategy = '1'. endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~LOG_MESSAGE. * Log message in the application log DATA lo_logger TYPE REF TO /iwbep/cl_cos_logger. DATA lv_text TYPE /iwbep/sup_msg_longtext. MESSAGE ID iv_msg_id TYPE iv_msg_type NUMBER iv_msg_number WITH iv_msg_v1 iv_msg_v2 iv_msg_v3 iv_msg_v4 INTO lv_text. lo_logger = mo_context->get_logger( ). lo_logger->log_message( EXPORTING iv_msg_type = iv_msg_type iv_msg_id = iv_msg_id iv_msg_number = iv_msg_number iv_msg_text = lv_text iv_msg_v1 = iv_msg_v1 iv_msg_v2 = iv_msg_v2 iv_msg_v3 = iv_msg_v3 iv_msg_v4 = iv_msg_v4 iv_agent = 'DPC' ). endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~RFC_EXCEPTION_HANDLING. * RFC call exception handling DATA lo_logger TYPE REF TO /iwbep/cl_cos_logger. lo_logger = /iwbep/if_mgw_conv_srv_runtime~get_logger( ). /iwbep/cl_sb_gen_dpc_rt_util=>rfc_exception_handling( EXPORTING iv_subrc = iv_subrc iv_exp_message_text = iv_exp_message_text io_logger = lo_logger ). endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~RFC_SAVE_LOG. DATA lo_logger TYPE REF TO /iwbep/cl_cos_logger. DATA lo_message_container TYPE REF TO /iwbep/if_message_container. lo_logger = /iwbep/if_mgw_conv_srv_runtime~get_logger( ). lo_message_container = /iwbep/if_mgw_conv_srv_runtime~get_message_container( ). "" Save the RFC call log in the application log /iwbep/cl_sb_gen_dpc_rt_util=>rfc_save_log( EXPORTING is_return = is_return iv_entity_type = iv_entity_type it_return = it_return it_key_tab = it_key_tab io_logger = lo_logger io_message_container = lo_message_container ). endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~SET_INJECTION. * Unit test injection IF io_unit IS BOUND. mo_injection = io_unit. ELSE. mo_injection = me. ENDIF. endmethod. method CHECK_SUBSCRIPTION_AUTHORITY. RAISE EXCEPTION TYPE /iwbep/cx_mgw_not_impl_exc EXPORTING textid = /iwbep/cx_mgw_not_impl_exc=>method_not_implemented method = 'CHECK_SUBSCRIPTION_AUTHORITY'. endmethod. method RULERUNNERKEYVAL_CREATE_ENTITY. RAISE EXCEPTION TYPE /iwbep/cx_mgw_not_impl_exc EXPORTING textid = /iwbep/cx_mgw_not_impl_exc=>method_not_implemented method = 'RULERUNNERKEYVAL_CREATE_ENTITY'. endmethod. method RULERUNNERKEYVAL_DELETE_ENTITY. RAISE EXCEPTION TYPE /iwbep/cx_mgw_not_impl_exc EXPORTING textid = /iwbep/cx_mgw_not_impl_exc=>method_not_implemented method = 'RULERUNNERKEYVAL_DELETE_ENTITY'. endmethod. method RULERUNNERKEYVAL_GET_ENTITY. RAISE EXCEPTION TYPE /iwbep/cx_mgw_not_impl_exc EXPORTING textid = /iwbep/cx_mgw_not_impl_exc=>method_not_implemented method = 'RULERUNNERKEYVAL_GET_ENTITY'. endmethod. method RULERUNNERKEYVAL_GET_ENTITYSET. RAISE EXCEPTION TYPE /iwbep/cx_mgw_not_impl_exc EXPORTING textid = /iwbep/cx_mgw_not_impl_exc=>method_not_implemented method = 'RULERUNNERKEYVAL_GET_ENTITYSET'. endmethod. method RULERUNNERKEYVAL_UPDATE_ENTITY. RAISE EXCEPTION TYPE /iwbep/cx_mgw_not_impl_exc EXPORTING textid = /iwbep/cx_mgw_not_impl_exc=>method_not_implemented method = 'RULERUNNERKEYVAL_UPDATE_ENTITY'. endmethod. ENDCLASS. ",4942,False,1042.9837554569874,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER (database | NAMESPACE) multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER (database | NAMESPACE) multipartIdentifier SET locationSpec #setNamespaceLocation | DROP (database | NAMESPACE) (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) namespace=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) namespace=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) (database | NAMESPACE) EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=RLIKE pattern=valueExpression | NOT? kind=LIKE pattern=valueExpression (ESCAPE escapeChar=STRING)? | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? | {SQL_standard_keyword_behavior}? (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval) ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER multipartIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPE | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12532,False,2342.0858109075175,median "# Instaclustr Esop image:https://img.shields.io/maven-central/v/com.instaclustr/esop.svg?label=Maven%20Central[link=https://search.maven.org/search?q=g:%22com.instaclustr%22%20AND%20a:%22esop%22] image:https://circleci.com/gh/instaclustr/esop.svg?style=svg[""Instaclustr"",link=""https://circleci.com/gh/instaclustr/esop""] _Swiss knife for Apache Cassandra backup and restore_ image::Esop.png[Esop,width=50%] - Website: https://www.instaclustr.com/ - Documentation: https://www.instaclustr.com/support/documentation/ This repository is home of backup and restoration tools from Instaclustr for Cassandra called https://en.wikipedia.org/wiki/Aesop[Esop] Esop is able to perform these operations and has these features: * Backup and restore of SSTables * Backup and restore of commit logs * Restoration of data into a Cassandra schema or diffrent table schema * Backing-up to and restoring from S3 (Oracle and Ceph via Object Gateway too), Azure, or GCP, or into any local destination or other storage providing they are easily implementable * listing of local backups and their removal, global removal of backups across all nodes in cluster * periodic removal of backups (e.g. after 10 days) * Effective upload and download—it will upload only SSTables which are not present remotely so any subsequent backups will upload and restores will download only the difference * When used in connection with https://github.com/instaclustr/icarus[Instaclustr Icarus] it is possible to backup **simultaneously** so there might be more concurrent backups which may overlap what they backup * Used as backup/restore solution in https://github.com/instaclustr/cassandra-operator[Instaclustr Cassandra Operator] for Kubernetes * Possible to restore whole node _from scratch_ (or whole cluster from scratch in cases where Kubernetes Operator is used) * In connection with Icarus, it is possible to **restore on a running cluster** so no downtime is necessary * It takes care of details such as initial tokens, auto bootstrapping, and so on... * Ability to throttle the bandwidth used for backup * Point-in-time restoration of commit logs * verification of downloaded data - computes hases upon upload and download and it has to match otherwise restoration fails * it is possible to restore tables under different names so they do not clash with your current tables ideal when you want to investigate / check data before you restore the original tables, to see what data you will have once you restore it * retry of failed operations against s3 when uploading / downloading failure happens This tool is used as a command line utility and it is meant to be executed from a shell or from scripts. However, this tooling is also embedded seamlessly into Instaclustr Icarus. The advantage of using Icarus is that you may backup and restore your node (or whole cluster) remotely by calling a respective REST endpoint so Icarus can execute respective backup or restore _operation_. Icarus is designed to be run alongside a node and it talks to Cassandra via JMX (no need to expose JMX publicly). In addition, this tool has to be run in the very same context/environment as a Cassandra node—it needs to see the whole directory structure of a node (data dir etc.) as it will upload these files during a backup and download them on a restore. If you want to be able to restore and backup remotely, use Icarus which embeds this project. ## Supporter Cassandra Versions Since we are talking to Cassandra via JMX, almost any Cassandra version is supported. We are testing this tool with Cassandra 3.11.8, 4.0-beta3, and 2.2.18. ## Usage Released artifact is on https://search.maven.org/artifact/com.instaclustr/esop[Maven Central]. You may want to build it on your own by standard Maven targets. After this project is built by `mvn clean install` (refer to <> for more details), the binary is in `target` and it is called `instaclustr-esop.jar`. This binary is all you need to backup/restore. It is the command line application, invoke it without any arguments to see help. You can invoke `help backup` for `backup` command, for example. ---- $ java -jar target/instaclustr-esop.jar Missing required subcommand. Usage:
[-V] COMMAND -V, --version print version information and exit Commands: backup Take a snapshot of this nodes Cassandra data and upload it to remote storage. Defaults to a snapshot of all keyspaces and their column families, but may be restricted to specific keyspaces or a single column-family. restore Restore the Cassandra data on this node to a specified point-in-time. commitlog-backup Upload archived commit logs to remote storage. commitlog-restore Restores archived commit logs to node. ---- ### Connecting to Cassandra Node As already mentioned, this tool expects to be invoked alongside a node—it needs to be able to read/write into Cassandra data directories. For other operations such as knowing tokens etc., it connects to respective node via JMX. By default, it will try to connect to `service:jmx:rmi:///jndi/rmi://127.0.0.1:7199/jmxrmi`. It is possible to override this and other related settings via the command line arguments. It is also possible to connect to such nodes securely if it is necessary, and this tool also supports specifying keystore, truststore, user name and password etc. For brevity, please consult the command line `help`. Not all sub-commands require the connection to Cassandra to exist. As of now, a JMX connection is necessary for: . backup of tables/keyspaces . restore of tables/keyspaces (hard linking and importing strategies) The next release of this tool might relax these requirements so it would be possible to backup and restore a node which is offline. For backup and restore of commit logs, it is not necessary to have a node up as well in case you need to restore a node _from scratch_ or if you use <>. ### Storage Location Data to backup and restore from, are located in a remote storage. This setting is controlled by flag `--storage-location`. The storage location flag has very specific structure which also indicates where data will be uploaded. Locations consist of a storage _protocol_ and path. Please keep in mind that the protocol we are using is not a _real_ protocol. It is merely a mnemonic. Use either `s3`, `gcp`, `azure`, `oracle`, `minio`, `ceph` or `file`. The format is: `protocol://bucket/cluster/datacenter/node` * `protocol` is either `s3`,`azure`,'gcp`, or `file. * `bucket` is name of the bucket data will be uploaded to/downloaded from, for example `my-bucket` * `cluster` is name of the cluster, for example, `test-cluster` * `datacenter` is name of the datacenter a node belongs to, for example `datacenter1` * `node` is identified of a node. It might be e.g. `1`, or it might be equal to node id (uuid) The structure of a storage location is validated upon every request. If we want to backup to S3, it would look like: `s3://cassandra-backups/test-cluster/datacenter1/1` In S3, data for that node will be stored under key `test-cluster/datacenter1/1`. The same mechanism works for other clouds. For `file` protocol, use `file:///data/backups/test-cluster/dc1/node1`. In every case, `file` has to start with full path (`file:///`, three slashes). File location does not have a notion of a _bucket_, but we are using it here regardless—in the following examples, the _bucket_ will be _a_. It does not matter you put slash at the end of whole location, it will be removed. .file path resolution |=== |storage location |path |file:///tmp/some/path/a/b/c/d |/tmp/some/path/a |file:///tmp/a/b/c/d |/tmp/a |=== ### Authentication Against a Cloud In order to be able to download from and upload to a remote bucket, this tool needs to pick up security credentials to do so. This varies across clouds. `file` protocol does not need any authentication. #### S3 The resolution of credentials for S3 uses the same resolution mechanism as the official AWS S3 client uses. The most notable fact is that if no credentials are set explicitly, it will try to resolve them from environment properties of the node it runs on. If that node runs in AWS EC2, it will resolve them by help of that particular instance. S3 connectors will expect to find environment properties `AWS_ACCESS_KEY_ID` and `AWS_SECRET_KEY`. They will also accept `AWS_REGION` and `AWS_ENDPOINT` environment properties—however they are not required. If `AWS_ENDPOINT` is set, `AWS_REGION` has to be set too. S3 currently supports two different addressing models: path-style and virtual-hosted style (https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAPI.html). Esop supports different S3 providers and applies the following default addressing models. .default settings per provider |=== |provider |addressing model |AWS |virtual |Ceph |virtual |Minio |path |Oracle |path |=== Providing the AWS_ENABLE_PATH_STYLE_ACCESS environment variable with `true` or `false` overrides this default setting. Note that this applies to each provider, except when running in Kubernetes. |provider|model| |Minio|path| The communication with S3 might be insecure, this is controlled by `--insecure-http` flag on the command line. By default, it uses HTTPS. It is possible to connect to S3 via proxy; please consult ""--use-proxy"" flag and ""--proxy-*"" family of settings on command line. #### Azure Azure module expects `AZURE_STORAGE_ACCOUNT` and `AZURE_STORAGE_KEY` environment variables to be set. #### GCP GCP module expects `GOOGLE_APPLICATION_CREDENTIALS` environment property or `google.application.credentials` to be set with the path to service account credentials. #### Oracle Oracle module behaves same way as S3 when it comes to credentials. #### Ceph CEPH module uses https://docs.ceph.com/en/latest/radosgw/s3/java/[Amazon S3 driver] for https://docs.ceph.com/en/latest/radosgw/[Ceph Object Gateway]. Credentials-wise, it behaves same way as ""normal"" S3. **You are required to set endpoint to AmazonS3 client.** In that case, be sure `AWS_ENDPOINT` environment property is set or `awsendpoint` property in Kubernetes secret is specified. You need to provide typical access key and secret key too. Please consult the following section to know more about Kubernetes-related authentication properties resolution. Setting protocol to HTTP might be achieved similarly as for normal S3 module, by specifying `--insecure-http` flag. #### Minio `minio` is alias of `oracle`. Oracle nor Minio uses path-style requests which S3 module does not. #### Authentication in Kubernetes If this tooling is run in the context of Kubernetes, we need to inject these credentials dynamically upon every request. If these credentials are not set statically, e.g. as environment or system properties, we may have an application like Cassandra Sidecar which resolves these credentials on every backup or restore request so they may change over time by Kubernetes operators (as person). By dynamic injecting, we are separating the lifecycle of a credential from the lifecycle of a backup/restore/Sidecar application. Credentials are stored as a secret. Namespace to read that secret from is specified by flag `--k8s-namespace` and the secret to read credentials from is specified by flag `--k8s-secret-name`. If namespace flag is not used, it defaults to `default`. If the secret name is not used, it is resolved as `cassandra-backup-restore-secret-cluster-\\{cluterId\\}` where `clusterId` is taken from cluster name in `--storage-location`. The secret has to contain these fields: ``` apiVersion: v1 kind: Secret metadata: name: cassandra-backup-restore-secret-cluster-my-cluster type: Opaque stringData: awssecretaccesskey: _AWS secret key_ awsaccesskeyid: _AWS access id_ awsregion: e.g. eu-central-1 awsendpoint: endpoint azurestorageaccount: _Azure storage account_ azurestoragekey: _Azure storage key_ gcp: 'whole json with service account' ``` Of course, if we do not plan to use other storage providers, feel free to omit the properties for them. For S3, only the secret key and access key are required. The fact that the code is running in the context of Kubernetes is derived from two facts: * there are environment properties `KUBERNETES_SERVICE_HOST` and `KUBERNETES_SERVICE_PORT` in a respective container this tool is invoked in * This tool runs outside of Kubernetes but as _a client_ meaning it will resolve credentials from there but it does not run in any container. This is helpful for example during tests where we do not run it inside Kubernetes but we want to be sure that the logic dealing with the credentials resolution works properly. This is controlled by system property `kubernetes.client` which is by default false. There might be the third (rather special) case—we want to run this tool in Kubernetes (so env properties would be there) but we want to run it as a client. Normally, the first condition would be fulfilled. There is a property called `pretend.not.running.in.kubernetes`, defaults to `false`. If set to true, even we run our tool in Kubernetes, it will act as a client, so it will not retrieve credentials from Kubernetes secret but from system and environment variables. ### Directory Structure of a Remote Destination Cassandra data files as well as some meta-data needed for successful restoration are uploaded into a bucket of a supported cloud provider (e.g. S3, Azure, or GCP) or they are copied to a local directory. Let's say we are in a bucket called `my-cassandra-backups` in Azure, and we did a backup with storage location set to `azure://test-cluster/dc1/1e519de1-58bb-40c5-8fc7-3f0a5b0ae7ee`. Snapshot name we set via `--snapshot-tag` was `snapshot3` and schema version of that node was `f1159959-593d-33d1-9ade-712ea55b31ef`. The content of that hypothetical bucket with same data will look like this: ``` . ├── topology │ └── snapshot3-f1159959-593d-33d1-9ade-712ea55b31ef-1600645759830.json (1) └── test-cluster └── dc1 ├── 1e519de1-58bb-40c5-8fc7-3f0a5b0ae7ee (2) │ ├── data │ │ ├── system │ │ | // data for this keyspace │ │ ├── system_auth │ │ | // data for this keyspace │ │ ├── system_schema │ │ | // data for this keyspace │ │ ├── test1 │ │ │ ├── testtable1-52d74870fb9911eaa75583ff20369112 │ │ │ │ ├── 1-2620247400 (3) │ │ │ │ │ ├── na-1-big-CompressionInfo.db │ │ │ │ │ ├── na-1-big-Data.db │ │ │ │ │ ├── na-1-big-Digest.crc32 │ │ │ │ │ ├── na-1-big-Filter.db │ │ │ │ │ ├── na-1-big-Index.db │ │ │ │ │ ├── na-1-big-Statistics.db │ │ │ │ │ ├── na-1-big-Summary.db │ │ │ │ │ └── na-1-big-TOC.txt │ │ │ │ ├── 1-4234234234 │ │ │ │ │ ├── // other SSTable │ │ │ │ └── schema.cql (4) │ │ │ ├── testtable2-545c13b0fb9911eaadb9b998490b71f5 │ │ │ │ // other table │ │ │ └── testtable3-55e8a720fb9911eaa2026b6b285d5a8a │ │ │ // other table │ │ └── test2 │ └── manifests (5) │ └── snapshot1-f1159959-593d-33d1-9ade-712ea55b31ef-1600645216879.json ├── 55d39d99-a9e1-44da-941c-3a46efed66b3 │ // other node ├── 59b5e477-df39-4126-acd4-726c937fe8fc │ // other node └── e8fd8bca-e6cb-4a1a-82db-192e2b4b77a5 ``` . When this tool is used in connection with Instaclustr Cassandra Sidecar, it also creates a _topology_ file. Topology file is needed for restoration into a Kubernetes cluster. . Data for each node are stored under that very node, here we used UUID identifier which is host ID as Cassandra sees it, and it is unique. Hence, it is impossible to accidentally store data for a different node as each node will have unique UUID. It may happen that over time we will have a cluster of same name and data center of same name but the node id would be still different so no clash would occur. . Each SSTable is stored in a directory . `schema.cql` contains a CQL ""create"" statement of that table as it looked upon a respective snapshot. It is there for diagnostic purposes so we might as well import data by other means than this tool as we would have to create that table in the first place before importing any data to it. . `manifests` directory holds JSON files which contain all files related to a snapshot as well other meta information. Its content will be discussed later. The directory where SSTable files are found, in our example for `test1.testtable1`, is `1-2620247400`. `1` means the generation, `2620247400` is crc checksum from `na-1-big-Digest.crc32`. Through this technique, every SSTable is totally unique and it ensures that they would not clash, even if they were named the same. This crc is inherently the part of the path where all files are, and a manifest file is pointing to them so we have a unique match. #### Manifest A manifest file is uploaded with all data. It contains all information necessary to restore that snapshot. Manifest name has this format: `snapshot3-f1159959-593d-33d1-9ade-712ea55b31ef-1600645759830.json` * `snapshot3`—name of snapshot used during a backup * `f1159959-593d-33d1-9ade-712ea55b31ef` schema version of Cassandra * `1600645759830` timestamp when that snapshot/backup was taken The content of a manifest file looks like this: ``` { ""snapshot"" : { ""name"" : ""snapshot3"", ""keyspaces"" : { ""ks1"" : { ""tables"" : { ""ks1t1"" : { ""entries"" : [ { ""objectKey"" : ""path-to/1-1146970048/na-1-big-CompressionInfo.db"", ""type"" : ""FILE"", ""size"" : 47 }, { ""objectKey"" : ""path-to/1-1146970048/na-1-big-Data.db"", ""type"" : ""FILE"", ""size"" : 53 }, { ""objectKey"" : ""path-to/schema.cql"", ""type"" : ""CQL_SCHEMA"", ""size"" : 934 } ], ""id"" : ""e17ff4b0e89211eab4313d37e7f4ac07"", ""schemaContent"" : ""CREATE TABLE IF NOT EXISTS ks1.ks1t1 ..."" }, ""ks1t2"" : { // other table } } } ""ks2"": { // other keyspace } } }, ""tokens"" : [ ""-1025679257793152318"", ""-126823146888567559"", .... ], ""schemaVersion"" : ""f1159959-593d-33d1-9ade-712ea55b31ef"" } ``` A manifest maps all resources related to a snapshot, their size as well as type (`FILE` or `CQL_SCHEMA`). It holds all schema content in a respective file too, so we do not need to read/parse the schema file as it is already a part of the manifest. Upon restore, this file is read into its Java model and _enriched_ by setting a path where each _manifest entry_ should be physically located on disk as we need to remove part of the file where a hash is specified. It is also possible to filter this manifest in such a way that we might backup 5 tables, but we want to restore only 2 of them so the other three tables would not be downloaded at all. #### Topology File Topology file is uploaded during a backup as well. It is uploaded into a bucket's `topology` directory in root. A topology file is provided not only as a reference to see what the topology was upon backup, but it also helps Instaclustr Cassandra operator to resolve which node it should download data for. If we are restoring a cluster from scratch and all we have is its former hostname, we need to know what was the node's id (`nodeId` below) because that id signifies which directory its data is stored in. When Instaclustr Cassandra operator restores a cluster from scratch, it knows a name of a pod (its hostname) but it does not know the id to load data from. The storage location upon a restore looks like `s3://bucket/test-cluster/dc1/cassandra-test-cluster-dc1-west1-b-0`. Internally, based on a snapshot and schema, we resolve the correct topology file and we filter its content to see which node starts on that hostname so we use, in this case, `nodeId` 8619f3e2-756b-4cb1-9b5a-4f1c1aa49af6 upon restoration. Storage location flag is then updated to use this node, so it will look like `s3://bucket/test-cluster/dc1/8619f3e2-756b-4cb1-9b5a-4f1c1aa49af6`. ``` { ""timestamp"" : 1600645216879, ""clusterName"" : ""test-cluster"", ""schemaVersion"" : ""f1159959-593d-33d1-9ade-712ea55b31ef"", ""topology"" : [ { ""hostname"" : ""cassandra-test-cluster-dc1-west1-b-0"", ""cluster"" : ""test-cluster"", ""dc"" : ""dc1"", ""rack"" : ""west1-b"", ""nodeId"" : ""8619f3e2-756b-4cb1-9b5a-4f1c1aa49af6"", ""ipAddress"" : ""10.244.2.82"" }, { ""hostname"" : ""cassandra-test-cluster-dc1-west1-a-0"", ""cluster"" : ""test-cluster"", ""dc"" : ""dc1"", ""rack"" : ""west1-a"", ""nodeId"" : ""b7952bdc-ccae-4443-9521-908820d067c1"", ""ipAddress"" : ""10.244.1.194"" }, { ""hostname"" : ""cassandra-test-cluster-dc1-west1-c-0"", ""cluster"" : ""test-cluster"", ""dc"" : ""dc1"", ""rack"" : ""west1-c"", ""nodeId"" : ""1e519de1-58bb-40c5-8fc7-3f0a5b0ae7ee"", ""ipAddress"" : ""10.244.2.83"" } ] } ``` A name of a topology file has this format `clusterName-snapshotName-schemaVersion-timestamp`. This uniquely identifies a topology in time. #### Resolving Manifest and Topology File From Backup Request Lets say we have done a backup against a node, multiple times, where some snapshot names were the same and schema version was the same too, for some cases we will have these manifests in a bucket: ``` ├── snapshot3-f1159959-593d-33d1-9ade-712ea55b31ef-1600645759830.json └── test-cluster └── dc1 └── 1e519de1-58bb-40c5-8fc7-3f0a5b0ae7ee └── manifests (5) ├─ snapshot1-f1159959-593d-33d1-9ade-712ea55b31ef-1600645216000.json ├─ snapshot1-f1159959-593d-33d1-9ade-712ea55b31ef-1600645217000.json ├─ snapshot1-b555c56d-a89f-4002-9f9c-0d4c78d3eca9-1600645217800.json ├─ snapshot2-f1159959-593d-33d1-9ade-712ea55b31ef-1600645218000.json ├─ snapshot3-f1159959-593d-33d1-9ade-712ea55b31ef-1600645219000.json └─ snapshot4-f1159959-593d-33d1-9ade-712ea55b31ef-1600645220000.json ``` Which manifest will be resolved when we use `snapshot1` as `--snapshot-tag`? If there are multiple manifests starting with same snapshot tag and having same schema version, in this particular case, it will pick the one with timestamp `1600645217800` as the latest manifest wins. You may specify `--snapshot-tag` as `snapshot1-f1159959-593d-33d1-9ade-712ea55b31ef` or even full version with timestamp. The longest prefix wins and when there are multiple manifests resolved, the latest wins. In case we have the same snapshot but different schema, only the snapshot name and schema version will be enough, not the snapshot name alone. By this logic, we are preventing the situation where two operators (as a person) will do two backups with the same snapshots against a node on the same schema version—the only information which makes these two requests unique is the timestamp. However, we may use just the same snapshot name (for practical reasons not recommended) and all would work just fine. The same resolution logic holds for topology file resolution—the longest prefix wins and it has to be uniquely filtered. Upon backup, the schema version is determined by calling respective JMX method. The user does not have to provide it on his own. On the other hand, the second way how to resolve the problems above during restoration is to specify `--exactSchemaVersion` flag. When set, it will try to filter only manifests which were done on the same schema version as a current node runs on. The last option is to use `--schema-version` option (in connection with `--exact-schema-version`) with the schema version manually. #### Backup The anatomy of a backup is quite simple. The successful invocation of `backup` sub-command will do the following: . Checks if a remote bucket for whatever storage provider exists, and will optionally create it if it doesn't (consult command line for help on how to achieve that). If a bucket does not exist and we are not allowed to create it automatically—the backup will fail. . Takes tokens of a respective node via JMX. Tokens are necessary for cases when we want to restore into a completely empty node. If we downloaded all data but tokens would be autogenerated, the data that node is supposed to serve would not match tokens that node is using. . Takes a snapshot of respective _entities_—either keyspaces or tables. It is not possible to mix keyspaces and some tables, it is _either_ keyspace(s) _or_ tables. This is inherited from the fact that Cassandra JMX API is designed that way. `nodetool snapshot` also permits us to specify entities to backup either as `ks1,ks2,ks3` or `ks1.t1,ks1.t2,ks2.t3` and we copy this behaviour here. The name of snapshot is auto generated when not specified via command line. . Creates internal mapping of snapshot to files it should upload. . Uploads SSTables and helper files to remote storage—only files which are not uploaded. By doing this, we will not ""over-upload"" as an SSTable is an immutable construct, so there is no need to upload what is already there. The backup procedure will check if a remote file is not there and uploads only in case it is not. Backup is doing a ""hash"" of an SSTable and it is uploaded under such key so it is not possible that two SSTables would be overwritten even if they are named the same as their hashes do not necessarily match. . The actual downloading/uploading is done in parallel—the number of simultaneous uploadings/downloadings is controlled by `concurrent-connections` setting which defaults to 10. It is possible to throttle the bandwidth so we do not use all available bandwidth for backups/restores so the node which might still be in operation would suffer performance-wise. . Writes meta-files to a remote storage—manifest and topology file (when Sidecar is used). . Clears taken snapshot. As of now, a node to be backed-up has to be online because we need tokens, we need to take a snapshot, etc. and this is done via JMX. In theory we do not need a node to be online if we take a snapshot beforehand and tokens are somehow provided externally, however the current version of the tool does require it. #### Restore This tool is seamlessly integrated into https://github.com/instaclustr/icarus[Icarus] which is able to do backup and restore in a distributed manner—cluster wide. Please refer to documentation of Icarus to understand what restoration phases are and what restoration strategies one might use. The very same restoration flow might be executed from CLI, Icarus just accepts a JSON payload which is a different representation of the very same data structure as the one used from command like but the functionality is completely the same. CLI tool is not responsive to `globalRequest` flag in restoration/backup requests—only Sidecar can coordinate cluster-wide restoration and backup. A restoration is a relatively more complex procedure than a backup. We have provided three _strategies_. You may control which strategy is used via command line. In general, the restoration is about: . Downloading data from remote location . Making Cassandra use these files While the first step is quite straightforward, the second depends on various factors we guide a reader through. Restoration strategy is determined by flag `--restoration-strategy-type` which might be `IN_PLACE`, `IMPORT`, or `HARDLINKS`, case-insensitive. #### In-Place Restoration Strategy In-place strategy must be used only in case a Cassandra node is _down_— Cassandra process does not run. This strategy will download only SSTables (and related files) which are not present locally, and it will directly download them to their respective data directories of a node. Then it will remove SSTables (and related files) which should not be there. As a backup is done against a _snapshot_; restore is also done from a snapshot. Use this strategy if you want to: * restore from an older snapshot and your node does not run * restore from a snapshot and your node is completely empty—it was never run/its `data` dir is empty * restore a cluster/node by Cassandra Operator. This feature is already fully embedded into our operator offering so one can restore whole clusters very conveniently. In more detail, in-place strategy does the following: . Checks that a remote bucket to download data from exists and errors out if it does not . In case `--resolve-host-id-from-topology` flag is used, it will resolve a host to restore from topology file. This is handy for cases we want to restore e.g. in the context of Kubernetes by our operator. . Downloads a manifest—manifest contains the list of files which are logically related to a snapshot. . Filters out the files which need to be downloaded, as some files which are present locally might be also a part of a taken snapshot so we would download them unnecessarily. . Downloads files directly into Cassandra `data` dir. . Deletes files from `data` dir which should not be there. . Cleans data in other directories—hints, saved caches, commit logs. . Updates `cassandra.yaml` if present with `auto_bootstrap: false` and `initial_token` with tokens from manifest. It is possible to restore not only user keyspaces and tables but system keyspaces too. This is necessary for the successful restoration of a cluster/node exactly as it was before as all system tables would be same. Normally, system keyspaces are not restored and one has to set this explicitly by `--restore-system-keyspace` flag. In-place strategy uses also `--restore-into-new-cluster` flag. If specified, it will restore only system keyspaces needed for successful restoring (`system_schema`) but it will not attempt to restore anything else. In an environment like Kubernetes, we do not want to restore _everything_ because system keyspaces contain details like tokens, peers with ips, etc. and this information is very specific to each one so we do not restore them. However, if we did not restore `system_schema`, the newly started node would not see the restored data as there would not be any schema. By restoring `system_schema`, Cassandra will detect these keyspaces and tables on the very first start. In-place restoration might update `cassandra.yaml` file if found. This is done automatically upon restoration in Cassandra operator but it might be required to be done manually for other cases. By default, `cassandra.yaml` is not updated. The updating is enabled by setting `--update-cassandra-yaml` flag upon restore. It is expected that `cassandra.yaml` is located in a directory `\\{cassandraConfigDirectory\\}/` (by default `/etc/cassandra`). The Cassandra configuration directory with `cassandra.yaml` might be changed via `--config-directory` flag. There are two options which are automatically changed when `cassanra.yaml` if found, in connection with this strategy: * `auto_bootstrap` - if not found, it will be appended and set to `false`. If found and set to `true`, it will be replaced by `false`. If `auto_bootstrap: false` is already present, nothing happens. * `initial_token`—set only in case it is not present `cassandra.yaml`. Tokens are set in order to have the node we are restoring to on the same tokens as the node we took a snapshot from. #### Hard-Linking Strategy This strategy is supposed to be executed against a _running_ node. Hard-linking strategy downloads data from a bucket to a node's local directory and it will make hardlinks from these files to Cassandra data dir for that keyspace/table. After hardlinks are done, it will _refresh_ a respective table / keyspace via JMX so Cassandra will start to read from them. Afterwards, the original files are deleted. This strategy works for Cassandra version 3 as well as for Cassandra 4. #### Importing Strategy This strategy is similar to hardlinking strategy — the node upon restoration can still run and serve other requests so a restoration process is not disruptive. _Importing_ means that it will import downloaded SSTables via JMX directly so no hardlinks and refresh are necessary. Importing of SSTables by calling respecting JMX method was introduced in Cassandra 4 only, so this does not work against a node of version 3 or below. Keep in mind that imported SSTables are physically deleted from download directory and moved to live Cassandra data directory. #### Restoration Phases for Hardlinking and Importing Strategy Hardlinking and importing strategy consists of _phases_. Each phase is done _per node_. . Cluster health check—this phase ensures that we are restoring into a healthy cluster, if any of this check is violated the restore will not proceed. We check that: .. A node under the restoration is in `NORMAL` state .. Each node in a cluster is `UP—the failure detector (as seen from that node) does not detect any node as failed .. All nodes are not in _joining_, _leaving_, _moving_ state and all are reachable .. All nodes are on same schema version . Downloading phase—this phase will download all data necessary for the restore to happen. . Truncate phase—this phase will truncate all respective tables we want to restore. . Importing phase—for hardlinking strategy. It will do hardlinks from download directory to live Cassandra data dir; for importing strategy, it will call JMX method to import them. . Cleaning phase—this phase will cleanup a directory where Cassandra put truncated data; it will also delete the directory where downloaded SSTables are. In a situation where we are restoring into a cluster of multiple nodes, the truncate operation should be executed only once against a particular node, as Cassandra will internally distribute the truncating operation to all nodes in a cluster. In other words, it is enough to truncate at one node only as data from all other nodes will be truncated too. Downloading phase is proceeding all other phases because we want to be sure that we are truncating the data if and only if we have all data to restore from. If we truncated all data and download fails, we can not restore and the node does not contain any data to serve, rendering it useless (for that table) with some complicated procedure to recover the truncated data. If any phases fail, all other phases fail too. Hence if we fail to download data, from an operational point of view nothing happens, as nothing was truncated and data on a running cluster were not touched. If we fail to truncate, we are still good. Once we truncate and we have all data, it is straightforward to import/hard-link data. This is the least invasive operation with a high probability of success. It can be decided if we want to delete downloaded as well as truncated data after a restore is finished. If we plan to restore multiple times with the same data—for whatever reason— and to return back to the same snapshot, it is not desired to download all data all over again. We might just reuse them. This is controlled by flags `--restoration-no-download-data` and `--restoration-no-delete-downloads` respectively. #### Restoring Into Different Schemas When a cluster we made a backup for is on the same schema at the time we want to do a restore, all is fine. However, a database schema evolves over time, columns are added or removed and we still want to be able to restore. Let's look at this scenario: . create keyspace `ks1` with table `table1` . insert data . make backup . alter table, **add** a column . insert data . restore into snapshot made in the 3rd step Clearly, the schema we are on differs from the schema back then—there is a new column which is not present in uploaded SSTables. However, this will work, resulting in a column which is new to have all values for that column as `null`. This tool does not try to modify a schema itself. An operator would have to take care of this manually and such column would have to be dropped. The opposite situation works as well: . create keyspace `ks1` with table `table1` . insert data . make backup . alter table, **drop** a column . insert data . restore into snapshot made in the 3rd step If we want to restore, we have one column less from snapshot, data will be imported but that column will just not be there. As of now, the restore is only ""forward-compatible"" on a table level. If we dropped whole table and we want to restore it, this is not possible—the table has to be there already. You may recreate them by applying respective CQL create statements from the manifest before proceeding. The tool might try to create these tables beforehand as we have that CQL schema at hand, but currently it is not implemented. ### Simultaneous Backups Backups are non-blocking. It means that multiple backups might be in progress. However, no file is uploaded in one particular moment more than once. Each backup request forms a _session_. A session contains _units_ to upload, referencing an entry in a manifest. If the second backup wants to upload the same file as the first one which is already uploading, it will just wait until the first backup is complete. The simultaneous restore is not finished yet. The power of simultaneous backups is fully understood in connection with Instaclustr Cassandra Sidecar as that is a server-like application running for a long period of time where an operator can submit backup requests which might happen at the same time (uploading of files is happening concurrently). CLI application does not profit from this feature. ### Resolution of Entities to Backup/Restore The flag `--entities` commands which database tables/keyspaces should be backed- up or restored. |=== |--entities |backup |restore |empty |all keyspaces and tables |all keyspaces and tables except `system*` |`ks1` |all tables in keyspace ks1 |all tables in keyspace ks1, except system keyspace |`ks1.t1,ks2.t2` |tables `t1` in `ks1` and table `t2` in `ks2` |tables `t1` in `ks1` and table `t2` in `ks2` |=== Moreover, if `--restore-system-keyspace` is set upon restore, it is possible to restore system keyspaces only in case `--restoration-strategy-type` is `IN_PLACE`. Logically, we can not restore system keyspaces on a running cluster in case we use hardlinking or importing strategy. System keyspaces are filtered out from entities automatically for these strategy types. However, if `IN_PLACE` strategy is used and flag `--restore-into-new-cluster` is specified, such strategy will pick only system keyspaces necessary for successful bootstrapping, as it restores `system_schema` only from all system schemas. `system_schema` needs to already contain the keyspaces and tables we are restoring. If we started a completely new node without restoring `system_schema`, it would not detect these imported keyspaces. Keep in mind that if system keyspace (`system_schema`) is not specified upon backup, it will not be uploaded; `--entities` need to enumerate all entities explicitly (or if it is empty, absolutely everything will be uploaded). ### Backup and Restore of Commit Logs It is possible to backup and restore commit logs too. There is a dedicated sub-command for this task. Please refer to examples how to invoke it. The commit logs are simply uploaded to a remote storage under node keys of the users choosing as specified in storage location property. The respective command does not derive the storage path on its own out of the box as commit logs might be uploaded even if a node is offline. So there might be no means to retrieve its host id via JMX, for example, but this might be turned on on demand. The example of backup (for brevity, we are showing just the sub-command): ---- $ commitlog-backup \\ --storage-location=s3://myBucket/mycluster/dc1/node1, \\ --data-directory=/my/installation/of/cassandra/data ---- Note that in this example, there is not any need to specify `--jmx-service` because it is not needed. JMX is needed for taking snapshots, for example, but here we do not take any. This command will expect `commitlog` directory under `--data-directory`. It is possible to override this by specifying `--cl-archive` with the path to the commit logs instead of expecting them to be under `--data-directory`. This plays nicely especially with the commit log archiving procedure of Cassandra. Let's say you have this in `commitlog_archiving.properties` file: ---- archive_command=/bin/ln %path /backup/%name ---- where `%path` is a fully qualified path of the segment to archive and `%name` is name of the commit log (these variables will be automatically expanded by Cassandra). Then you might archive your commit logs like this: ---- $ commitlog-backup \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --cl-archive=/backup ---- The backup logic will iterate over all commit logs in `/backup` and it will try to refresh them in the remote store, if they are refreshed, it means they are already uploaded. If refreshing fails, that commit log is not there so it will be uploaded. You might as well script this in such a way that a commit log would be automatically uploaded as part of Cassandra archiving procedure, like this: ---- archive_command=/bin/bash /path/to/my/backup-script.sh %path %name ---- The content of `backup-script.sh` might look like: ---- $!/bin/bash java -jar instaclustr-esop.jar commitlog-backup \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --commit-log=$1 ---- There is one improvement to do here, even if we do not know what the host id or dc or name of a cluster is, this can be found out dynamically as part of the backup by specifying `--online` flag (if a Cassandra node is online it just archived a commit log for us). ---- $!/bin/bash # specifying --online will update s3://myBucket/mycluster/dc1/node1 to # s3://myBucket/real-dc/real-dc-name/68fcbda0-442f-4ca4-86ec-ec46f2a00a71 where uuid is host id. java -jar instaclustr-backup-restore.jar commitlog-backup \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --commit-log=$1 \\ --online ---- ### Examples of Command Line Invocation Each example shown here should be prepended with `java -jar instaclustr-esop.jar`. We are showing here just respective commands. This command will copy over all SSTables to the remote location. It is also possible to choose a location in a cloud. For backup, a node has to be up to back it up. ---- backup \\ --jmx-service 127.0.0.1:7199 \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --data-directory=/my/installation/of/cassandra \\ --entities=ks1,ks2 \\ --snapshot-tag=mysnapshot ---- If you want to upload SSTables into AWS, GCP, or Azure, just change protocol to either `s3`, `gcp`, or `azure`. The first part of the path is the bucket you want to upload files to, for `s3`, it would be like `s3://bucket-for-my-cluster/cluster-name/dc-name/node-id`. If you want to use a different cloud, just change the protocol respectively. We also support https://docs.cloud.oracle.com/en-us/iaas/Content/Object/Tasks/s3compatibleapi.htm[Oracle cloud]; use `oracle://` protocol for your backup and restores. We also support CEPH S3 Gateway, use `ceph://` protocol for your backup and restores. If a bucket does not exist, it will be created only when `--create-missing-bucket` is specified. The verification of a bucket might be skipped by flag `--skip-bucket-verification`. If the verification is not skipped (which is default) and we detect that a bucket does not exist, the operation fails if we do not specify `--create-missing-bucket` flag. ### Example of `commitlog-backup` You can backup commit logs as well. An example of a commit log backup is like the following: ---- $ commitlog-backup \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --data-directory=/my/installation/of/cassandra ---- Note that there is no need to specify jmx-service. JMX is needed for taking snapshots, but here we do not take any. ### Example of in-place `restore` The restoration of a node is achieved by following parameters: ---- $ restore --data-directory=/my/installation/of/restored-cassandra/data \\ --config-directory=/my/installation/of/restored-cassandra/conf \\ --snapshot-tag=stefansnapshot"" \\ --storage-location=s3://bucket-name/cluster-name/dc-name/node-id \\ --restore-system-keyspace \\ --update-cassandra-yaml=true"" ---- Notice a few things here: * there is implicity used `--restoration-strategy-type=IN_PLACE` * `--snapshot-tag` is specified. Normally, when snapshot name is not used upon backup, there is a snapshot taken of some generated name. You would have to check the name of a snapshot in a backup location to specify it yourself, so it is better to specify that beforehand and just reference it. * `--update-cassandra-yaml` is set to true, this will automatically set `initial_tokens` in `cassandra.yaml` for the restored node. If it is false, you will have to set it up yourself, copying the content of tokens file in backup directory, under `tokens` directory. * `--restore-system-keyspace` is specified, which means it will restore system keyspaces too, which is not normally done. This might be specified only for IN_PLACE strategy as that strategy requires a node to be down and we can manipulate system keyspaces only on such a node. ### Example of Hardlinking and Importing Restoration Hardlinking as well as importing restoration consists of phases. These strategies expect a Cassandra node to be up and fully operational. The primary goal of these strategies is to restore on a _running node_, so the restoration procedure does not require a node to be offline which greatly increases the availablity of the whole cluster. Backup and restore will look like the following: ---- backup \\ --jmx-service 127.0.0.1:7199 \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --data-directory=/my/installation/of/cassandra \\ --entities=ks1,ks2 \\ --snapshot-tag=mysnapshot ---- The first restoration phase is DOWNLOAD as we need to download remote SSTables: ---- restore \\ --data-directory=/path/to/cassandra/data \\ --snapshot-tag=my-snapshot \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --entities=ks1,ks2 \\ --restoration-strategy-type=hardlinks \\ --restoration-phase-type=download, /// IMPORTANT --import-source-dir=/where/to/put/downloaded/sstables ---- Then we need to truncate `ks1` and `ks2`: ---- restore, --data-directory=/path/to/cassandra/data \\ --snapshot-tag=my-snapshot \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --entities=ks1,ks2 \\ --restoration-strategy-type=hardlinks \\ --restoration-phase-type=truncate \\ /// IMPORTANT --import-source-dir=/where/to/put/downloaded/sstables ---- Once we truncate keyspaces, we can make hardlinks from directory where we downloaded SSTables to the Cassandra data directory: ---- restore, --data-directory=/path/to/cassandra/data \\ --snapshot-tag=my-snapshot \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --entities=ks1,ks2 \\ --restoration-strategy-type=hardlinks \\ --restoration-phase-type=import \\ /// IMPORTANT --import-source-dir=/where/to/put/downloaded/sstables ---- Lastly we can cleanup downloaded data as well as truncated as they are not needed anymore: ---- restore, --data-directory=/path/to/cassandra/data \\ --snapshot-tag=my-snapshot \\ --storage-location=s3://myBucket/mycluster/dc1/node1 \\ --entities=ks1,ks2 \\ --restoration-strategy-type=hardlinks \\ --restoration-phase-type=cleanup \\ /// IMPORTANT --import-source-dir=/where/to/put/downloaded/sstables ---- If you check this closely you see that the only flag we have changed is `--restoration-phase-type` and that is correct. All commands will look exactly the same but they will just differ on `--restoration-phase-type`. If we wanted to do a restore via Cassandra JMX _importing_, our `--restoration-strategy-type` would be `import`. ### Renaming of a table to restore to It is possible to restore to a different table you backed up. This feature is very handy for cases when you want to examine data before you actually restore them - you might put them temporarily to a different table to see if all is right etc. From Esop CLI, you drive this feature by flag called `--rename`. This flag might repeat as many times as many times you need to rename. This feature might be used only for hardlinks or importing strategy, not for in-place. A table has to exist before a restore action is taken. Esop does **not** create this table for you automatically and it is left for a user to ensure such table exists before proceeding. Let's say you have backed up a table called `tb1` in a keyspace called `ks1` but you want to restore it into table `tb2` in the same keyspace. Hence you need to specify `--rename=ks1.tb1=ks1.tb2`. `--rename` options is meant to be used along with `--entities`. It is a valid scenario to do this: These examples show invalid cases for the combination of `--entities` and `--renamed` ---- --entities="""" --rename=whatever non empty -> invalid --entities=ks1 --rename=whatever non empty -> invalid, you can not use only a keyspace in --entities --entities=ks1.tb1 --rename=ks1.tb2=ks1.tb2 -> invalid as ""from"" is not in entities --entities=ks1.tb1 --rename=ks1.tb2=ks1.tb1 -> invalid as ""to"" is in entities (and from is not in entities) --entities=ks1.tb1 --rename=ks1.tb1=ks1.tb2 -> truncate ks1.tb2 and process just ks1.tb2, k1.tb1 is not touched ---- Valid cases: ---- --entities=ks1.tb1 --rename=ks1.tb1=ks1.tb2 --entities=ks1.tb1 --rename=ks1.tb1=ks2.tb1 --entities=ks1.tb1,ks2.tb2,ks3.tb4 --rename=ks1.tb1=ks1.tb2,ks2.tb2=ks3.tb3 ---- * entities in ""to"" have to be unique across all renaming pairs, ""ks1.tb1=ks1.tb2,ks1.tb3=ks1.tb2"" is invalid * please keep in mind that if you are doing cross-keyspace renaming, as of now you are completely on your own when it comes to e.g. replication factors etc, Esop currently does not check that replication factor and replication strategy in source and target keyspace match. This might be addressed in the future versions. From Icarus point of view, you need to add a map under ""rename"" field: ---- { ""rename"": { ""ks1.tb1"": ""ks1.tb2"", ""ks2.tb3"": ""ks2.tb4"", ""ks3.tb5"": ""ks3.tb6"" } } ---- ### Skipping refreshment of remote objects By default, Esop ""refreshes"" remote objects. Refreshment means that the last modification date of a remote object will be updated to the time the backup was done. This is done because we need to somehow detect if a remote file already exists or not. If it does, we do not upload it. If it does not exist, we upload it. However, if it does exist, we need to update the modification date because there might be, for example, a retention policy on remote objects in a bucket to be set for some period of time (for example, 14 days) and if a particular files not touched for 14 days, it would be removed. This way you might automatically implement the deletion of older backups because if there is a newer backup consisting of a set of SSTables, all SSTables which were previously a part of the older backup but they are not a part of the current backup would not be touched - hence no modification date would be refreshed - so they would expire. For cases there is a versioning enabled (currently known to be an issue for S3 backups only), our attempt to refresh it would create new, versioned, file. This is not desired. Hence we have the possibility to skip refreshment and we just detect if a file is there or not, but you would lose the ability to expire objects as described above. This behavior is controlled by flag called `--skip-refreshing` on backup command. By default, when not specified, it is evaluated to `false`, so skipping would not happen. ### Retry of upload / download operations Imagine there is a restore happening which is downloading 100 GB of data and your connectivity to the Internet is disrupted when it is almost done, on 80%. If you restart whole restoration process, you do not want to download all 80 GB again. Hence, we want that if a restore is stopped in the middle, it will not start from scratch next time we run it and it will download what is necessary. As a result of these errors, a file might be corrupted, it may be incomplete on the disk so its loading or hard linking into Cassandra would fail. To be sure that data are not corrupted, there is a hash (sha512) of that file made and it is uploaded as part of the manifest. Upon restore, if that file already exists locally, it computes the has and it compares it withe the one in the manifest and they have to match. If they do not match, such corrupted file is deleted and whole operation as such (download phase in case of import or hardlinks strategy) fails. On the next restore attempt, it will skip files which are in download directory already present and donwloads ony missing ones, computing their hashes etc ... On backup path, if a communication error happens, this is also detected and operation fails as such but some files might be already uploaded. On next upload, Esop checks if such file is already present remotely and it will skip it from uploading if it does. If upload of a file fails, Esop can _retry_. The mechanism how this happens is controlled by the family of ""--retry-*"" switches on the command line. In a nutshell, your retry might be exponential or linear. The exponential retry will execute the same operation (e.g. uploading of a file) every time exponentially it terms of the pause between retries. Linear retry has the retry period constant. ### Explanation of Global Requests It looks like the phases are an unnecessary hassle to go through, but the granularity is required in case we are executing a so called _global request_. A global request is used in the context of Cassandra Sidecar and it does not have any usage during CLI executions. ### Example of `commitlog-restore` The restoration of commit logs can be done like this: ---- $ commitlog-restore --data-directory=/my/installation/of/restored-cassandra/data --config-directory=/my/installation/of/restored-cassandra/conf --storage-location=s3://bucket-name/cluster-name/dc-name/node-id --commitlog-download-dir=/dir/where/commitlogs/are/downloaded --timestamp-end=unix_timestamp_of_last_transaction_to_replay ---- The commit log restorations are driven by Cassandra's `commitlog_archiving.properties` file. This tool will generate such files into the node's `conf` directory so it will be read upon node start. After a node is restored in this manner, one has to *delete* `commitlog_archiving.properties` file in order to prevent commitlog replay by accident again if a node is restarted. ---- restore_directories=/home/smiklosovic/dev/instaclustr-esop/target/commitlog_download_dir restore_point_in_time=2020\\:01\\:13 11\\:32\\:51 restore_command=cp -f %from %to ---- ## Listing of backups This feature is for now only available for `file://`-based backups. Listing of a bucket provides a better visibility into what backups there are, how may files they are consisting of and how much space they occupy as well as how many space we would reclaim by their deletion. ---- $ java -jar ~/esop.jar list \\ --storage-location=file:///backup1/cluster/datacenter1/node1 \\ --skip-node-resolution \\ --human-units Timestamp Name Files Occupied space Reclaimable space 2021-04-27T15:38:40.284 name-of-backup-1 154 113.1 kB 10.1 kB 2021-04-27T15:38:20.259 name-of-backup-2 138 103.0 kB 0 B 154 113.1 kB ---- Listing of a backup will read all manifests there are for a respective node and it will compute the statistics above. It is important to understand that the figure representing the number of files for a specific backup does not represent the unique files. Since a backup can have SSTables present in more than one backup, the sum of files per backup does not need to match the global number of files. Above we see that backup1 has 154 files and backup2 has 138 files but in total there is 154 files. This means that backup2 is logically consisting of SSTables which are all in backup1 and backup1 contains all SSTables in backup2 plus some new ones. Same holds for occupied space. The figure of reclaimable space represents the number of bytes (or any human readable size) which would be freed by deleting that particular backup. For example, from the above we see that by deleting backup-2, we would get no free space. Why? Because all SSTables in backup-2 also belongs to backup-1. So we can not just physically remove it because backup-1 would just be corrupted. On the other hand, by deletion of backup-1, we would gain 10.1 kB. Why? Because we just can not go and delete all SSTables belonging to backup-1, because backup-2 would be corrupted - it would miss SStables. We can safely delete only these files from backup-1 which are not in backup-2 - and that difference occupies just 10 kB. However, we see that in total, our data occupy 113 kB at disk even though the sum of occupied space of all backups does not match the total - because there are SSTables logically belonging to multiple backups. Please keep in mind that this table reflects the reality as long as you do not add nor delete any backup. |=== |flag |explanation |--skip-node-resolution |Skips the resolution of cluster name, data center and host id of a node Esop is connected to, otherwise it will try to connect to that node and retrieve this information and it will replace respective placeholders in --storage-location property. |--simple-format |prints out just names of backups instead of all statistics |--json |prints out a json instead of a table |--human-units |prints human-friendly sizes, e.g 5 kB, 1 GB etc instead of just number of bytes |--to-file |path to file to redirect the output of the command to, file is created when it does not exist |--from-timestamp |expects unix timestamp (also present in backup's name at the end), once set, it will only process backups taken since then, including. |--last-n |expects a postive integer to process only last (the oldest) n backups. |=== All `--json`, `--simple-format` and `--to-file` might be freely turned on / off on demand. By default, it will print a table in complex format to the standard output. `list` command is receptive to all family of `--jmx-*` settings in order to connect to a running Cassandra node if necessary. ## Removal of a backup Since we are storing each SSTable only once, ever, a deletion of a backup is not so straightforward. We might delete only SSTable which is present only in one backup. If some particular SSTable is present in multiple backups, we might delete that backup _logically_, but we can not delete that SSTable. The underlying logic computes how may backups a particular file is present it by scanning all manifests there are and if we specify we want to delete so and so backup, it will physically remove only files which are part of that very backup and they are not present anywhere else. By doing this, we are not forced to remove only the last backup (for example looking at its timestamp) but we can in general remove any backup. The general workflow is to either list all backups and remove only the one you want, or you can specify `--oldest` to delete the oldest one and you can do this repeatedly. If you want to remove all backups older than some time, you might get this information from listing the backups by specifying `--from-timestamp` and then you can delete these backups one by one. ---- $ java -jar ~/esop.jar remove-backup \\ --storage-location=file:///backup1/cluster/datacenter1/node1 \\ --skip-node-resolution \\ --backup-name=full-backup-name-from-listing-with-timestamp-etc ---- All flags: |=== |flag |explanation |--backup-name |name of manifest file to delete a backup for (minus .json) |--oldest |removes oldest backup there is, backup names does not need to be specified then |--dry |it will not delete files for real, good for evaluation to see what it would do before shooting |--skip-node-resolution |consult list command, same logic |=== ## Global removal of backups From the previous section, you know how to delete an individual backup. However, it would be nice to be able to delete, for example, all backups older than 14 days, globaly. ""Globally"" means that it will scan whole local backup destination of all nodes (all dcs). You have the option to either do individual removal or global removal. For global removal of backups older than 14 days: [source,bash] ---- $ esop remove-backup \\ --global-request \\ --skip-node-resolution \\ --storage-location=file:///submit/backup/Test-Cluster/dc1/ab3f1d62-1a61-4f84-a2e2-97a626940d8d \\ --older-than=14day ---- It is enough to specify one node, all other nodes will be resolved automatically. `--older-than` accepts a format like ""number+unit"", for example ""1h"", ""1minute"". If you want to run this in a daemon mode - meaning this operation would be run repeatedly, you need to execute it like this: [source,bash] ---- $ esop remove-backup \\ --global-request \\ --skip-node-resolution \\ --storage-location=file:///submit/backup/Test-Cluster/dc1/ab3f1d62-1a61-4f84-a2e2-97a626940d8d \\ --older-than=5minute \\ --rate=1minute ---- This means it will execute a backup removal every 1 minute and it will delete all backups older than 5 minutes. For more real scenarios you might specify `--older-than=14day` and `--rate=1day`. The time for the next execution will count down from the time this command was firstly executed. You have also possibility to specify datacenters to remove by `--dcs` flag (might be specified multiple times for each dc separately) ## Logging We are using logback. There is already `logback.xml` embedded in the built JAR. However if you want to configure it, feel free to provide your own `logback.xml` and configure it like this: ---- java -Dlogback.configurationFile=my-custom-logback.xml \\ -jar instaclustr-backup-restore.jar backup ---- You can find the original file in `src/main/resources/logback.xml`. ## Build and Test There are end-to-end tests which can test all GCP, Azure, and S3 integrations as well as integrations with Kubernetes when it comes to credential fetching. Here are the test groups/profiles: * azureTests * googleTest * s3Tests * cloudTest—runs tests which will be using cloud ""buckets"" for backup / restore * k8sTest—same as `cloudTest` above, but credentials will be fetched from Kubernetes. There is no need to create buckets in a cloud beforehand as they will be created and deleted as part of a test automatically, per cloud provider. If a test is ""Kubernetes-aware"", before every test credentials are created as a Secret which will be used by backup/restore tooling during a test. We are simulating here how this tooling can be easily embedded into for example Cassandra Sidecar (part of Cassandra operator). We are avoiding the need to specify credentials upfront when a Kubernetes pod is starting as a part of that spec, by dynamically fetching all credentials from a Secret whose name is passed to a backup request and is read every time. The side-effect of this is that we can change our credentials without restarting a pod to re-read them because they will be read dynamically upon every backup request. Cloud tests are executed like this: ---- $ mvn clean install -PcloudTests ---- Kubernetes tests are executed like this: ---- $ mvn clean install -Pk8sTests ---- By default, `mvn install` is invoked with `noCloudTests` which will skip all tests dealing with storage provides but `file://`. You have to specify these system properties to run these tests successfully: ---- -Dawsaccesskeyid={your aws access key id} -Dawssecretaccesskey={your aws secret access key} -Dgoogle.application.credentials={path to google application credentials file on local disk} -Dazurestorageaccount={your azure storage account} -Dazurestoragekey={your azure storage key} ---- In order to skip tests altogether, invoke the build like `mvn clean install -DskipTests`. User can use a Maven wrapper script so all Maven will be downloaded automatically. The build in that case is run as `./mvnw clean install`. If you want to build rpm or deb package, you need to enable `rpm` and/or `deb` Maven profile. ## Further Information - Please see https://www.instaclustr.com/support/documentation/announcements/instaclustr-open-source-project-status/ for Instaclustr support status of this project - See Data Backup Documentation (https://www.instaclustr.com/support/documentation/cassandra/cassandra-cluster-operations/cluster-data-backups/) ",16340,True,2727.397391127038,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER (database | NAMESPACE) multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER (database | NAMESPACE) multipartIdentifier SET locationSpec #setNamespaceLocation | DROP (database | NAMESPACE) (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) namespace=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) namespace=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) (database | NAMESPACE) EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? | {SQL_standard_keyword_behavior}? (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval) ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER multipartIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12505,False,2336.886397404185,median "tag::aggregations[] If set, the {dfeed} performs aggregation searches. Support for aggregations is limited and should be used only with low cardinality data. For more information, see {ml-docs}/ml-configuring-aggregation.html[Aggregating data for faster performance]. end::aggregations[] tag::allow-lazy-open[] Advanced configuration option. Specifies whether this job can open when there is insufficient {ml} node capacity for it to be immediately assigned to a node. The default value is `false`; if a {ml} node with capacity to run the job cannot immediately be found, the <> returns an error. However, this is also subject to the cluster-wide `xpack.ml.max_lazy_ml_nodes` setting; see <>. If this option is set to `true`, the <> does not return an error and the job waits in the `opening` state until sufficient {ml} node capacity is available. end::allow-lazy-open[] tag::allow-lazy-start[] Whether this job should be allowed to start when there is insufficient {ml} node capacity for it to be immediately assigned to a node. The default is `false`, which means that the <> will return an error if a {ml} node with capacity to run the job cannot immediately be found. (However, this is also subject to the cluster-wide `xpack.ml.max_lazy_ml_nodes` setting - see <>.) If this option is set to `true` then the <> will not return an error, and the job will wait in the `starting` state until sufficient {ml} node capacity is available. end::allow-lazy-start[] tag::allow-no-datafeeds[] Specifies what to do when the request: + -- * Contains wildcard expressions and there are no {dfeeds} that match. * Contains the `_all` string or no identifiers and there are no matches. * Contains wildcard expressions and there are only partial matches. The default value is `true`, which returns an empty `datafeeds` array when there are no matches and the subset of results when there are partial matches. If this parameter is `false`, the request returns a `404` status code when there are no matches or only partial matches. -- end::allow-no-datafeeds[] tag::allow-no-jobs[] Specifies what to do when the request: + -- * Contains wildcard expressions and there are no jobs that match. * Contains the `_all` string or no identifiers and there are no matches. * Contains wildcard expressions and there are only partial matches. The default value is `true`, which returns an empty `jobs` array when there are no matches and the subset of results when there are partial matches. If this parameter is `false`, the request returns a `404` status code when there are no matches or only partial matches. -- end::allow-no-jobs[] tag::allow-no-match[] Specifies what to do when the request: + -- * Contains wildcard expressions and there are no {dfanalytics-jobs} that match. * Contains the `_all` string or no identifiers and there are no matches. * Contains wildcard expressions and there are only partial matches. The default value is `true`, which returns an empty `data_frame_analytics` array when there are no matches and the subset of results when there are partial matches. If this parameter is `false`, the request returns a `404` status code when there are no matches or only partial matches. -- end::allow-no-match[] tag::analysis[] Defines the type of {dfanalytics} you want to perform on your source index. For example: `outlier_detection`. See <>. end::analysis[] tag::analysis-config[] The analysis configuration, which specifies how to analyze the data. After you create a job, you cannot change the analysis configuration; all the properties are informational. end::analysis-config[] tag::analysis-limits[] Limits can be applied for the resources required to hold the mathematical models in memory. These limits are approximate and can be set per job. They do not control the memory used by other processes, for example the {es} Java processes. end::analysis-limits[] tag::assignment-explanation-anomaly-jobs[] For open {anomaly-jobs} only, contains messages relating to the selection of a node to run the job. end::assignment-explanation-anomaly-jobs[] tag::assignment-explanation-datafeeds[] For started {dfeeds} only, contains messages relating to the selection of a node. end::assignment-explanation-datafeeds[] tag::assignment-explanation-dfanalytics[] Contains messages relating to the selection of a node. end::assignment-explanation-dfanalytics[] tag::background-persist-interval[] Advanced configuration option. The time between each periodic persistence of the model. The default value is a randomized value between 3 to 4 hours, which avoids all jobs persisting at exactly the same time. The smallest allowed value is 1 hour. + -- TIP: For very large models (several GB), persistence could take 10-20 minutes, so do not set the `background_persist_interval` value too low. -- end::background-persist-interval[] tag::bucket-allocation-failures-count[] The number of buckets for which new entities in incoming data were not processed due to insufficient model memory. This situation is also signified by a `hard_limit: memory_status` property value. end::bucket-allocation-failures-count[] tag::bucket-count[] The number of buckets processed. end::bucket-count[] tag::bucket-count-anomaly-jobs[] The number of bucket results produced by the job. end::bucket-count-anomaly-jobs[] tag::bucket-span[] The size of the interval that the analysis is aggregated into, typically between `5m` and `1h`. The default value is `5m`. If the {anomaly-job} uses a {dfeed} with {ml-docs}/ml-configuring-aggregation.html[aggregations], this value must be divisible by the interval of the date histogram aggregation. For more information, see {ml-docs}/ml-buckets.html[Buckets]. end::bucket-span[] tag::bucket-span-results[] The length of the bucket in seconds. This value matches the `bucket_span` that is specified in the job. end::bucket-span-results[] tag::bucket-time-exponential-average[] Exponential moving average of all bucket processing times, in milliseconds. end::bucket-time-exponential-average[] tag::bucket-time-exponential-average-hour[] Exponentially-weighted moving average of bucket processing times calculated in a 1 hour time window, in milliseconds. end::bucket-time-exponential-average-hour[] tag::bucket-time-maximum[] Maximum among all bucket processing times, in milliseconds. end::bucket-time-maximum[] tag::bucket-time-minimum[] Minimum among all bucket processing times, in milliseconds. end::bucket-time-minimum[] tag::bucket-time-total[] Sum of all bucket processing times, in milliseconds. end::bucket-time-total[] tag::by-field-name[] The field used to split the data. In particular, this property is used for analyzing the splits with respect to their own history. It is used for finding unusual values in the context of the split. end::by-field-name[] tag::calendar-id[] A string that uniquely identifies a calendar. end::calendar-id[] tag::categorization-analyzer[] If `categorization_field_name` is specified, you can also define the analyzer that is used to interpret the categorization field. This property cannot be used at the same time as `categorization_filters`. The categorization analyzer specifies how the `categorization_field` is interpreted by the categorization process. The syntax is very similar to that used to define the `analyzer` in the <>. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. + The `categorization_analyzer` field can be specified either as a string or as an object. If it is a string it must refer to a <> or one added by another plugin. If it is an object it has the following properties: + .Properties of `categorization_analyzer` [%collapsible%open] ===== `char_filter`:::: (array of strings or objects) include::{docdir}/ml/ml-shared.asciidoc[tag=char-filter] `tokenizer`:::: (string or object) include::{docdir}/ml/ml-shared.asciidoc[tag=tokenizer] `filter`:::: (array of strings or objects) include::{docdir}/ml/ml-shared.asciidoc[tag=filter] ===== end::categorization-analyzer[] tag::categorization-examples-limit[] The maximum number of examples stored per category in memory and in the results data store. The default value is 4. If you increase this value, more examples are available, however it requires that you have more storage available. If you set this value to `0`, no examples are stored. + NOTE: The `categorization_examples_limit` only applies to analysis that uses categorization. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. end::categorization-examples-limit[] tag::categorization-field-name[] If this property is specified, the values of the specified field will be categorized. The resulting categories must be used in a detector by setting `by_field_name`, `over_field_name`, or `partition_field_name` to the keyword `mlcategory`. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. end::categorization-field-name[] tag::categorization-filters[] If `categorization_field_name` is specified, you can also define optional filters. This property expects an array of regular expressions. The expressions are used to filter out matching sequences from the categorization field values. You can use this functionality to fine tune the categorization by excluding sequences from consideration when categories are defined. For example, you can exclude SQL statements that appear in your log files. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. This property cannot be used at the same time as `categorization_analyzer`. If you only want to define simple regular expression filters that are applied prior to tokenization, setting this property is the easiest method. If you also want to customize the tokenizer or post-tokenization filtering, use the `categorization_analyzer` property instead and include the filters as `pattern_replace` character filters. The effect is exactly the same. end::categorization-filters[] tag::categorization-status[] The status of categorization for the job. Contains one of the following values: + -- * `ok`: Categorization is performing acceptably well (or not being used at all). * `warn`: Categorization is detecting a distribution of categories that suggests the input data is inappropriate for categorization. Problems could be that there is only one category, more than 90% of categories are rare, the number of categories is greater than 50% of the number of categorized documents, there are no frequently matched categories, or more than 50% of categories are dead. -- end::categorization-status[] tag::categorized-doc-count[] The number of documents that have had a field categorized. end::categorized-doc-count[] tag::char-filter[] One or more <>. In addition to the built-in character filters, other plugins can provide more character filters. This property is optional. If it is not specified, no character filters are applied prior to categorization. If you are customizing some other aspect of the analyzer and you need to achieve the equivalent of `categorization_filters` (which are not permitted when some other aspect of the analyzer is customized), add them here as <>. end::char-filter[] tag::compute-feature-influence[] If `true`, the feature influence calculation is enabled. Defaults to `true`. end::compute-feature-influence[] tag::chunking-config[] {dfeeds-cap} might be required to search over long time periods, for several months or years. This search is split into time chunks in order to ensure the load on {es} is managed. Chunking configuration controls how the size of these time chunks are calculated and is an advanced configuration option. + .Properties of `chunking_config` [%collapsible%open] ==== `mode`::: (string) include::{docdir}/ml/ml-shared.asciidoc[tag=mode] `time_span`::: (<>) include::{docdir}/ml/ml-shared.asciidoc[tag=time-span] ==== end::chunking-config[] tag::class-assignment-objective[] Defines the objective to optimize when assigning class labels. Available objectives are `maximize_accuracy` and `maximize_minimum_recall`. When maximizing accuracy class labels are chosen to maximize the number of correct predictions. When maximizing minimum recall labels are chosen to maximize the minimum recall for any class. Defaults to maximize_minimum_recall. end::class-assignment-objective[] tag::custom-rules[] An array of custom rule objects, which enable you to customize the way detectors operate. For example, a rule may dictate to the detector conditions under which results should be skipped. For more examples, see {ml-docs}/ml-configuring-detector-custom-rules.html[Customizing detectors with custom rules]. end::custom-rules[] tag::custom-rules-actions[] The set of actions to be triggered when the rule applies. If more than one action is specified the effects of all actions are combined. The available actions include: * `skip_result`: The result will not be created. This is the default value. Unless you also specify `skip_model_update`, the model will be updated as usual with the corresponding series value. * `skip_model_update`: The value for that series will not be used to update the model. Unless you also specify `skip_result`, the results will be created as usual. This action is suitable when certain values are expected to be consistently anomalous and they affect the model in a way that negatively impacts the rest of the results. end::custom-rules-actions[] tag::custom-rules-scope[] An optional scope of series where the rule applies. A rule must either have a non-empty scope or at least one condition. By default, the scope includes all series. Scoping is allowed for any of the fields that are also specified in `by_field_name`, `over_field_name`, or `partition_field_name`. To add a scope for a field, add the field name as a key in the scope object and set its value to an object with the following properties: end::custom-rules-scope[] tag::custom-rules-scope-filter-id[] The id of the filter to be used. end::custom-rules-scope-filter-id[] tag::custom-rules-scope-filter-type[] Either `include` (the rule applies for values in the filter) or `exclude` (the rule applies for values not in the filter). Defaults to `include`. end::custom-rules-scope-filter-type[] tag::custom-rules-conditions[] An optional array of numeric conditions when the rule applies. A rule must either have a non-empty scope or at least one condition. Multiple conditions are combined together with a logical `AND`. A condition has the following properties: end::custom-rules-conditions[] tag::custom-rules-conditions-applies-to[] Specifies the result property to which the condition applies. The available options are `actual`, `typical`, `diff_from_typical`, `time`. If your detector uses `lat_long`, `metric`, `rare`, or `freq_rare` functions, you can only specify conditions that apply to `time`. end::custom-rules-conditions-applies-to[] tag::custom-rules-conditions-operator[] Specifies the condition operator. The available options are `gt` (greater than), `gte` (greater than or equals), `lt` (less than) and `lte` (less than or equals). end::custom-rules-conditions-operator[] tag::custom-rules-conditions-value[] The value that is compared against the `applies_to` field using the `operator`. end::custom-rules-conditions-value[] tag::custom-settings[] Advanced configuration option. Contains custom meta data about the job. For example, it can contain custom URL information as shown in {ml-docs}/ml-configuring-url.html[Adding custom URLs to {ml} results]. end::custom-settings[] tag::data-description[] The data description defines the format of the input data when you send data to the job by using the <> API. Note that when configure a {dfeed}, these properties are automatically set. When data is received via the <> API, it is not stored in {es}. Only the results for {anomaly-detect} are retained. + .Properties of `data_description` [%collapsible%open] ==== `format`::: (string) Only `JSON` format is supported at this time. `time_field`::: (string) The name of the field that contains the timestamp. The default value is `time`. `time_format`::: (string) include::{docdir}/ml/ml-shared.asciidoc[tag=time-format] ==== end::data-description[] tag::data-frame-analytics[] An array of {dfanalytics-job} resources, which are sorted by the `id` value in ascending order. + .Properties of {dfanalytics-job} resources [%collapsible%open] ==== `analysis`::: (object) The type of analysis that is performed on the `source`. //Begin analyzed_fields `analyzed_fields`::: (object) Contains `includes` and/or `excludes` patterns that select which fields are included in the analysis. + .Properties of `analyzed_fields` [%collapsible%open] ===== `excludes`::: (Optional, array) An array of strings that defines the fields that are excluded from the analysis. `includes`::: (Optional, array) An array of strings that defines the fields that are included in the analysis. ===== //End analyzed_fields //Begin dest `dest`::: (string) The destination configuration of the analysis. + .Properties of `dest` [%collapsible%open] ===== `index`::: (string) The _destination index_ that stores the results of the {dfanalytics-job}. `results_field`::: (string) The name of the field that stores the results of the analysis. Defaults to `ml`. ===== //End dest `id`::: (string) The unique identifier of the {dfanalytics-job}. `model_memory_limit`::: (string) The `model_memory_limit` that has been set to the {dfanalytics-job}. `source`::: (object) The configuration of how the analysis data is sourced. It has an `index` parameter and optionally a `query` and a `_source`. + .Properties of `source` [%collapsible%open] ===== `index`::: (array) Index or indices on which to perform the analysis. It can be a single index or index pattern as well as an array of indices or patterns. `query`::: (object) The query that has been specified for the {dfanalytics-job}. The {es} query domain-specific language (<>). This value corresponds to the query object in an {es} search POST body. By default, this property has the following value: `{""match_all"": {}}`. `_source`::: (object) Contains the specified `includes` and/or `excludes` patterns that select which fields are present in the destination. Fields that are excluded cannot be included in the analysis. + .Properties of `_source` [%collapsible%open] ====== `excludes`::: (array) An array of strings that defines the fields that are excluded from the destination. `includes`::: (array) An array of strings that defines the fields that are included in the destination. ====== //End of _source ===== //End source ==== end::data-frame-analytics[] tag::data-frame-analytics-stats[] An array of statistics objects for {dfanalytics-jobs}, which are sorted by the `id` value in ascending order. //Begin analysis_stats `analysis_stats`:: (object) An object containing statistical data about the analysis. + .Properties of `analysis_stats` [%collapsible%open] ==== //Begin classification_stats `classification_stats`::: (object) An object containing statistical data about the {classanalysis}. + .Properties of `classification_stats` [%collapsible%open] ===== //Begin class_hyperparameters `hyperparameters`:::: (object) An object containing the parameters of the {classanalysis}. + .Properties of `hyperparameters` [%collapsible%open] ====== tag::dfas-alpha[] `alpha`:::: (double) Regularization factor to penalize deeper trees when training decision trees. end::dfas-alpha[] `class_assignment_objective`:::: (string) Defines whether class assignment maximizes the accuracy or the minimum recall metric. Possible values are `maximize_accuracy` and `maximize_minimum_recall`. tag::dfas-downsample-factor[] `downsample_factor`:::: (double) The value of the downsample factor. end::dfas-downsample-factor[] tag::dfas-eta[] `eta`:::: (double) The value of the eta hyperparameter. end::dfas-eta[] tag::dfas-eta-growth[] `eta_growth_rate_per_tree`:::: (double) Specifies the rate at which the `eta` increases for each new tree that is added to the forest. For example, a rate of `1.05` increases `eta` by 5%. end::dfas-eta-growth[] tag::dfas-feature-bag-fraction[] `feature_bag_fraction`:::: (double) The fraction of features that is used when selecting a random bag for each candidate split. end::dfas-feature-bag-fraction[] tag::dfas-gamma[] `gamma`:::: (double) Regularization factor to penalize trees with large numbers of nodes. end::dfas-gamma[] tag::dfas-lambda[] `lambda`:::: (double) Regularization factor to penalize large leaf weights. end::dfas-lambda[] tag::dfas-max-attempts[] `max_attempts_to_add_tree`:::: (integer) If the algorithm fails to determine a non-trivial tree (more than a single leaf), this parameter determines how many of such consecutive failures are tolerated. Once the number of attempts exceeds the threshold, the forest training stops. end::dfas-max-attempts[] tag::dfas-max-optimization-rounds[] `max_optimization_rounds_per_hyperparameter`:::: (integer) A multiplier responsible for determining the maximum number of hyperparameter optimization steps in the Bayesian optimization procedure. The maximum number of steps is determined based on the number of undefined hyperparameters times the maximum optimization rounds per hyperparameter. end::dfas-max-optimization-rounds[] tag::dfas-max-trees[] `max_trees`:::: (integer) The maximum number of trees in the forest. end::dfas-max-trees[] tag::dfas-num-folds[] `num_folds`:::: (integer) The maximum number of folds for the cross-validation procedure. end::dfas-num-folds[] tag::dfas-num-splits[] `num_splits_per_feature`:::: (integer) Determines the maximum number of splits for every feature that can occur in a decision tree when the tree is trained. end::dfas-num-splits[] tag::dfas-soft-limit[] `soft_tree_depth_limit`:::: (double) Tree depth limit is used for calculating the tree depth penalty. This is a soft limit, it can be exceeded. end::dfas-soft-limit[] tag::dfas-soft-tolerance[] `soft_tree_depth_tolerance`:::: (double) Tree depth tolerance is used for calculating the tree depth penalty. This is a soft limit, it can be exceeded. end::dfas-soft-tolerance[] ====== //End class_hyperparameters tag::dfas-iteration[] `iteration`:::: (integer) The number of iterations on the analysis. end::dfas-iteration[] tag::dfas-timestamp[] `timestamp`:::: (date) The timestamp when the statistics were reported in milliseconds since the epoch. end::dfas-timestamp[] //Begin class_timing_stats tag::dfas-timing-stats[] `timing_stats`:::: (object) An object containing time statistics about the {dfanalytics-job}. end::dfas-timing-stats[] + .Properties of `timing_stats` [%collapsible%open] ====== tag::dfas-timing-stats-elapsed[] `elapsed_time`:::: (integer) Runtime of the analysis in milliseconds. end::dfas-timing-stats-elapsed[] tag::dfas-timing-stats-iteration[] `iteration_time`:::: (integer) Runtime of the latest iteration of the analysis in milliseconds. end::dfas-timing-stats-iteration[] ====== //End class_timing_stats //Begin class_validation_loss tag::dfas-validation-loss[] `validation_loss`:::: (object) An object containing information about validation loss. end::dfas-validation-loss[] + .Properties of `validation_loss` [%collapsible%open] ====== tag::dfas-validation-loss-type[] `loss_type`:::: (string) The type of the loss metric. For example, `binomial_logistic`. end::dfas-validation-loss-type[] tag::dfas-validation-loss-fold[] `fold_values`:::: (array of strings) Validation loss values for every added decision tree during the forest growing procedure. end::dfas-validation-loss-fold[] ====== //End class_validation_loss ===== //End classification_stats //Begin outlier_detection_stats `outlier_detection_stats`::: (object) An object containing statistical data about the {oldetection} job. + .Properties of `outlier_detection_stats` [%collapsible%open] ===== //Begin parameters `parameters`:::: (object) The list of job parameters specified by the user or determined by algorithmic heuristics. + .Properties of `parameters` [%collapsible%open] ====== `compute_feature_influence`:::: (boolean) If true, feature influence calculation is enabled. `feature_influence_threshold`:::: (double) The minimum {olscore} that a document needs to have to calculate its feature influence score. `method`:::: (string) The method that {oldetection} uses. Possible values are `lof`, `ldof`, `distance_kth_nn`, `distance_knn`, and `ensemble`. `n_neighbors`:::: (integer) The value for how many nearest neighbors each method of {oldetection} uses to calculate its outlier score. `outlier_fraction`:::: (double) The proportion of the data set that is assumed to be outlying prior to {oldetection}. `standardization_enabled`:::: (boolean) If true, then the following operation is performed on the columns before computing {olscores}: (x_i - mean(x_i)) / sd(x_i). ====== //End parameters include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timestamp] //Begin od_timing_stats include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timing-stats] + .Property of `timing_stats` [%collapsible%open] ====== include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timing-stats-elapsed] ====== //End od_timing_stats ===== //End outlier_detection_stats //Begin regression_stats `regression_stats`::: (object) An object containing statistical data about the {reganalysis}. + .Properties of `regression_stats` [%collapsible%open] ===== //Begin reg_hyperparameters `hyperparameters`:::: (object) An object containing the parameters of the {reganalysis}. + .Properties of `hyperparameters` [%collapsible%open] ====== include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-alpha] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-downsample-factor] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-eta] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-eta-growth] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-feature-bag-fraction] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-gamma] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-lambda] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-max-attempts] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-max-optimization-rounds] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-max-trees] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-num-folds] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-num-splits] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-soft-limit] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-soft-tolerance] ====== //End reg_hyperparameters include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-iteration] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timestamp] //Begin reg_timing_stats include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timing-stats] + .Propertis of `timing_stats` [%collapsible%open] ====== include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timing-stats-elapsed] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timing-stats-iteration] ====== //End reg_timing_stats //Begin reg_validation_loss include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-validation-loss] + .Properties of `validation_loss` [%collapsible%open] ====== include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-validation-loss-type] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-validation-loss-fold] ====== //End reg_validation_loss ===== //End regression_stats ==== //End analysis_stats `assignment_explanation`::: (string) For running jobs only, contains messages relating to the selection of a node to run the job. //Begin data_counts `data_counts`::: (object) An object containing statistical data about the documents in the analysis. + .Properties of `data_counts` [%collapsible%open] ==== `skipped_docs_count`::: (integer) The number of documents that are skipped during the analysis because they contained values that are not supported by the analysis. For example, {oldetection} does not support missing fields so it skips documents with missing fields. Likewise, all types of analysis skip documents that contain arrays with more than one element. `test_docs_count`::: (integer) The number of documents that are not used for training the model and can be used for testing. `training_docs_count`::: (integer) The number of documents that are used for training the model. ==== //End data_counts `id`::: (string) The unique identifier of the {dfanalytics-job}. `memory_usage`::: (Optional, object) An object describing memory usage of the analytics. It is present only after the job is started and memory usage is reported. `memory_usage`.`peak_usage_bytes`::: (long) The number of bytes used at the highest peak of memory usage. `memory_usage`.`timestamp`::: (date) The timestamp when memory usage was calculated. `node`::: (object) Contains properties for the node that runs the job. This information is available only for running jobs. `node`.`attributes`::: (object) Lists node attributes such as `ml.machine_memory`, `ml.max_open_jobs`, and `xpack.installed`. `node`.`ephemeral_id`::: (string) The ephemeral id of the node. `node`.`id`::: (string) The unique identifier of the node. `node`.`name`::: (string) The node name. `node`.`transport_address`::: (string) The host and port where transport HTTP connections are accepted. `progress`::: (array) The progress report of the {dfanalytics-job} by phase. `progress`.`phase`::: (string) Defines the phase of the {dfanalytics-job}. Possible phases: `reindexing`, `loading_data`, `analyzing`, and `writing_results`. `progress`.`progress_percent`::: (integer) The progress that the {dfanalytics-job} has made expressed in percentage. `state`::: (string) Current state of the {dfanalytics-job}. end::data-frame-analytics-stats[] tag::datafeed-id[] A numerical character string that uniquely identifies the {dfeed}. This identifier can contain lowercase alphanumeric characters (a-z and 0-9), hyphens, and underscores. It must start and end with alphanumeric characters. end::datafeed-id[] tag::datafeed-id-wildcard[] Identifier for the {dfeed}. It can be a {dfeed} identifier or a wildcard expression. end::datafeed-id-wildcard[] tag::dead-category-count[] The number of categories created by categorization that will never be assigned again because another category's definition makes it a superset of the dead category. (Dead categories are a side effect of the way categorization has no prior training.) end::dead-category-count[] tag::decompress-definition[] Specifies whether the included model definition should be returned as a JSON map (`true`) or in a custom compressed format (`false`). Defaults to `true`. end::decompress-definition[] tag::delayed-data-check-config[] Specifies whether the {dfeed} checks for missing data and the size of the window. For example: `{""enabled"": true, ""check_window"": ""1h""}`. + The {dfeed} can optionally search over indices that have already been read in an effort to determine whether any data has subsequently been added to the index. If missing data is found, it is a good indication that the `query_delay` option is set too low and the data is being indexed after the {dfeed} has passed that moment in time. See {ml-docs}/ml-delayed-data-detection.html[Working with delayed data]. + This check runs only on real-time {dfeeds}. + .Properties of `delayed_data_check_config` [%collapsible%open] ==== `check_window`:: (<>) The window of time that is searched for late data. This window of time ends with the latest finalized bucket. It defaults to `null`, which causes an appropriate `check_window` to be calculated when the real-time {dfeed} runs. In particular, the default `check_window` span calculation is based on the maximum of `2h` or `8 * bucket_span`. `enabled`:: (boolean) Specifies whether the {dfeed} periodically checks for delayed data. Defaults to `true`. ==== end::delayed-data-check-config[] tag::dependent-variable[] Defines which field of the document is to be predicted. This parameter is supplied by field name and must match one of the fields in the index being used to train. If this field is missing from a document, then that document will not be used for training, but a prediction with the trained model will be generated for it. It is also known as continuous target variable. end::dependent-variable[] tag::desc-results[] If true, the results are sorted in descending order. end::desc-results[] tag::description-dfa[] A description of the job. end::description-dfa[] tag::dest[] The destination configuration, consisting of `index` and optionally `results_field` (`ml` by default). + .Properties of `dest` [%collapsible%open] ==== `index`::: (Required, string) Defines the _destination index_ to store the results of the {dfanalytics-job}. `results_field`::: (Optional, string) Defines the name of the field in which to store the results of the analysis. Defaults to `ml`. ==== end::dest[] tag::detector-description[] A description of the detector. For example, `Low event rate`. end::detector-description[] tag::detector-field-name[] The field that the detector uses in the function. If you use an event rate function such as `count` or `rare`, do not specify this field. + -- NOTE: The `field_name` cannot contain double quotes or backslashes. -- end::detector-field-name[] tag::detector-index[] A unique identifier for the detector. This identifier is based on the order of the detectors in the `analysis_config`, starting at zero. end::detector-index[] tag::earliest-record-timestamp[] The timestamp of the earliest chronologically input document. end::earliest-record-timestamp[] tag::empty-bucket-count[] The number of buckets which did not contain any data. If your data contains many empty buckets, consider increasing your `bucket_span` or using functions that are tolerant to gaps in data such as `mean`, `non_null_sum` or `non_zero_count`. end::empty-bucket-count[] tag::eta[] Advanced configuration option. The shrinkage applied to the weights. Smaller values result in larger forests which have better generalization error. However, the smaller the value the longer the training will take. For more information about shrinkage, see https://en.wikipedia.org/wiki/Gradient_boosting#Shrinkage[this wiki article]. end::eta[] tag::exclude-frequent[] Contains one of the following values: `all`, `none`, `by`, or `over`. If set, frequent entities are excluded from influencing the anomaly results. Entities can be considered frequent over time or frequent in a population. If you are working with both over and by fields, then you can set `exclude_frequent` to `all` for both fields, or to `by` or `over` for those specific fields. end::exclude-frequent[] tag::exclude-interim-results[] If `true`, the output excludes interim results. By default, interim results are included. end::exclude-interim-results[] tag::feature-bag-fraction[] Advanced configuration option. Defines the fraction of features that will be used when selecting a random bag for each candidate split. end::feature-bag-fraction[] tag::feature-influence-threshold[] The minimum {olscore} that a document needs to have in order to calculate its {fiscore}. Value range: 0-1 (`0.1` by default). end::feature-influence-threshold[] tag::field-selection[] An array of objects that explain selection for each field, sorted by the field names. + .Properties of `field_selection` objects [%collapsible%open] ==== `is_included`::: (boolean) Whether the field is selected to be included in the analysis. `is_required`::: (boolean) Whether the field is required. `feature_type`::: (string) The feature type of this field for the analysis. May be `categorical` or `numerical`. `mapping_types`::: (string) The mapping types of the field. `name`::: (string) The field name. `reason`::: (string) The reason a field is not selected to be included in the analysis. ==== end::field-selection[] tag::filter[] One or more <>. In addition to the built-in token filters, other plugins can provide more token filters. This property is optional. If it is not specified, no token filters are applied prior to categorization. end::filter[] tag::filter-id[] A string that uniquely identifies a filter. end::filter-id[] tag::forecast-total[] The number of individual forecasts currently available for the job. A value of `1` or more indicates that forecasts exist. end::forecast-total[] tag::frequency[] The interval at which scheduled queries are made while the {dfeed} runs in real time. The default value is either the bucket span for short bucket spans, or, for longer bucket spans, a sensible fraction of the bucket span. For example: `150s`. When `frequency` is shorter than the bucket span, interim results for the last (partial) bucket are written then eventually overwritten by the full bucket results. If the {dfeed} uses aggregations, this value must be divisible by the interval of the date histogram aggregation. end::frequency[] tag::frequent-category-count[] The number of categories that match more than 1% of categorized documents. end::frequent-category-count[] tag::from[] Skips the specified number of {dfanalytics-jobs}. The default value is `0`. end::from[] tag::function[] The analysis function that is used. For example, `count`, `rare`, `mean`, `min`, `max`, and `sum`. For more information, see {ml-docs}/ml-functions.html[Function reference]. end::function[] tag::gamma[] Advanced configuration option. Regularization parameter to prevent overfitting on the training dataset. Multiplies a linear penalty associated with the size of individual trees in the forest. The higher the value the more training will prefer smaller trees. The smaller this parameter the larger individual trees will be and the longer train will take. end::gamma[] tag::groups[] A list of job groups. A job can belong to no groups or many. end::groups[] tag::include-model-definition[] Specifies if the model definition should be returned in the response. Defaults to `false`. When `true`, only a single model must match the ID patterns provided, otherwise a bad request is returned. end::include-model-definition[] tag::indices[] An array of index names. Wildcards are supported. For example: `[""it_ops_metrics"", ""server*""]`. + -- NOTE: If any indices are in remote clusters then `node.remote_cluster_client` must not be set to `false` on any {ml} nodes. -- end::indices[] tag::indices-options[] Specifies index expansion options that are used during search. + -- For example: ``` { ""expand_wildcards"": [""all""], ""ignore_unavailable"": true, ""allow_no_indices"": ""false"", ""ignore_throttled"": true } ``` For more information about these options, see <>. -- end::indices-options[] tag::inference-config-classification-num-top-classes[] Specifies the number of top class predictions to return. Defaults to 0. end::inference-config-classification-num-top-classes[] tag::inference-config-classification-num-top-feature-importance-values[] Specifies the maximum number of {ml-docs}/dfa-classification.html#dfa-classification-feature-importance[feature importance] values per document. By default, it is zero and no feature importance calculation occurs. end::inference-config-classification-num-top-feature-importance-values[] tag::inference-config-classification-top-classes-results-field[] Specifies the field to which the top classes are written. Defaults to `top_classes`. end::inference-config-classification-top-classes-results-field[] tag::inference-config-regression-num-top-feature-importance-values[] Specifies the maximum number of {ml-docs}/dfa-regression.html#dfa-regression-feature-importance[feature importance] values per document. By default, it is zero and no feature importance calculation occurs. end::inference-config-regression-num-top-feature-importance-values[] tag::inference-config-results-field[] The field that is added to incoming documents to contain the inference prediction. Defaults to `predicted_value`. end::inference-config-results-field[] tag::influencers[] A comma separated list of influencer field names. Typically these can be the by, over, or partition fields that are used in the detector configuration. You might also want to use a field name that is not specifically named in a detector, but is available as part of the input data. When you use multiple detectors, the use of influencers is recommended as it aggregates results for each influencer entity. end::influencers[] tag::input-bytes[] The number of bytes of input data posted to the {anomaly-job}. end::input-bytes[] tag::input-field-count[] The total number of fields in input documents posted to the {anomaly-job}. This count includes fields that are not used in the analysis. However, be aware that if you are using a {dfeed}, it extracts only the required fields from the documents it retrieves before posting them to the job. end::input-field-count[] tag::input-record-count[] The number of input documents posted to the {anomaly-job}. end::input-record-count[] tag::invalid-date-count[] The number of input documents with either a missing date field or a date that could not be parsed. end::invalid-date-count[] tag::is-interim[] If `true`, this is an interim result. In other words, the results are calculated based on partial input data. end::is-interim[] tag::job-id-anomaly-detection[] Identifier for the {anomaly-job}. end::job-id-anomaly-detection[] tag::job-id-data-frame-analytics[] Identifier for the {dfanalytics-job}. end::job-id-data-frame-analytics[] tag::job-id-anomaly-detection-default[] Identifier for the {anomaly-job}. It can be a job identifier, a group name, or a wildcard expression. If you do not specify one of these options, the API returns information for all {anomaly-jobs}. end::job-id-anomaly-detection-default[] tag::job-id-data-frame-analytics-default[] Identifier for the {dfanalytics-job}. If you do not specify this option, the API returns information for the first hundred {dfanalytics-jobs}. end::job-id-data-frame-analytics-default[] tag::job-id-anomaly-detection-list[] An identifier for the {anomaly-jobs}. It can be a job identifier, a group name, or a comma-separated list of jobs or groups. end::job-id-anomaly-detection-list[] tag::job-id-anomaly-detection-wildcard[] Identifier for the {anomaly-job}. It can be a job identifier, a group name, or a wildcard expression. end::job-id-anomaly-detection-wildcard[] tag::job-id-anomaly-detection-wildcard-list[] Identifier for the {anomaly-job}. It can be a job identifier, a group name, a comma-separated list of jobs or groups, or a wildcard expression. end::job-id-anomaly-detection-wildcard-list[] tag::job-id-anomaly-detection-define[] Identifier for the {anomaly-job}. This identifier can contain lowercase alphanumeric characters (a-z and 0-9), hyphens, and underscores. It must start and end with alphanumeric characters. end::job-id-anomaly-detection-define[] tag::job-id-data-frame-analytics-define[] Identifier for the {dfanalytics-job}. This identifier can contain lowercase alphanumeric characters (a-z and 0-9), hyphens, and underscores. It must start and end with alphanumeric characters. end::job-id-data-frame-analytics-define[] tag::job-id-datafeed[] The unique identifier for the job to which the {dfeed} sends data. end::job-id-datafeed[] tag::lambda[] Advanced configuration option. Regularization parameter to prevent overfitting on the training dataset. Multiplies an L2 regularisation term which applies to leaf weights of the individual trees in the forest. The higher the value the more training will attempt to keep leaf weights small. This makes the prediction function smoother at the expense of potentially not being able to capture relevant relationships between the features and the {depvar}. The smaller this parameter the larger individual trees will be and the longer train will take. end::lambda[] tag::last-data-time[] The timestamp at which data was last analyzed, according to server time. end::last-data-time[] tag::latency[] The size of the window in which to expect data that is out of time order. The default value is 0 (no latency). If you specify a non-zero value, it must be greater than or equal to one second. For more information about time units, see <>. + -- NOTE: Latency is only applicable when you send data by using the <> API. -- end::latency[] tag::latest-empty-bucket-timestamp[] The timestamp of the last bucket that did not contain any data. end::latest-empty-bucket-timestamp[] tag::latest-record-timestamp[] The timestamp of the latest chronologically input document. end::latest-record-timestamp[] tag::latest-sparse-record-timestamp[] The timestamp of the last bucket that was considered sparse. end::latest-sparse-record-timestamp[] tag::max-empty-searches[] If a real-time {dfeed} has never seen any data (including during any initial training period) then it will automatically stop itself and close its associated job after this many real-time searches that return no documents. In other words, it will stop after `frequency` times `max_empty_searches` of real-time operation. If not set then a {dfeed} with no end time that sees no data will remain started until it is explicitly stopped. By default this setting is not set. end::max-empty-searches[] tag::max-trees[] Advanced configuration option. Defines the maximum number of trees the forest is allowed to contain. The maximum value is 2000. end::max-trees[] tag::memory-estimation[] An object containing the memory estimates. + .Properties of `memory_estimation` [%collapsible%open] ==== `expected_memory_with_disk`::: (string) Estimated memory usage under the assumption that overflowing to disk is allowed during {dfanalytics}. `expected_memory_with_disk` is usually smaller than `expected_memory_without_disk` as using disk allows to limit the main memory needed to perform {dfanalytics}. `expected_memory_without_disk`::: (string) Estimated memory usage under the assumption that the whole {dfanalytics} should happen in memory (i.e. without overflowing to disk). ==== end::memory-estimation[] tag::method[] Sets the method that {oldetection} uses. If the method is not set {oldetection} uses an ensemble of different methods and normalises and combines their individual {olscores} to obtain the overall {olscore}. We recommend to use the ensemble method. Available methods are `lof`, `ldof`, `distance_kth_nn`, `distance_knn`. end::method[] tag::missing-field-count[] The number of input documents that are missing a field that the {anomaly-job} is configured to analyze. Input documents with missing fields are still processed because it is possible that not all fields are missing. + -- NOTE: If you are using {dfeeds} or posting data to the job in JSON format, a high `missing_field_count` is often not an indication of data issues. It is not necessarily a cause for concern. -- end::missing-field-count[] tag::mode[] There are three available modes: + -- * `auto`: The chunk size is dynamically calculated. This is the default and recommended value. * `manual`: Chunking is applied according to the specified `time_span`. * `off`: No chunking is applied. -- end::mode[] tag::model-bytes[] The number of bytes of memory used by the models. This is the maximum value since the last time the model was persisted. If the job is closed, this value indicates the latest size. end::model-bytes[] tag::model-bytes-exceeded[] The number of bytes over the high limit for memory usage at the last allocation failure. end::model-bytes-exceeded[] tag::model-id[] The unique identifier of the trained {infer} model. end::model-id[] tag::model-memory-limit[] The approximate maximum amount of memory resources that are required for analytical processing. Once this limit is approached, data pruning becomes more aggressive. Upon exceeding this limit, new entities are not modeled. The default value for jobs created in version 6.1 and later is `1024mb`. This value will need to be increased for jobs that are expected to analyze high cardinality fields, but the default is set to a relatively small size to ensure that high resource usage is a conscious decision. The default value for jobs created in versions earlier than 6.1 is `4096mb`. + If you specify a number instead of a string, the units are assumed to be MiB. Specifying a string is recommended for clarity. If you specify a byte size unit of `b` or `kb` and the number does not equate to a discrete number of megabytes, it is rounded down to the closest MiB. The minimum valid value is 1 MiB. If you specify a value less than 1 MiB, an error occurs. For more information about supported byte size units, see <>. + If your `elasticsearch.yml` file contains an `xpack.ml.max_model_memory_limit` setting, an error occurs when you try to create jobs that have `model_memory_limit` values greater than that setting. For more information, see <>. end::model-memory-limit[] tag::model-memory-limit-anomaly-jobs[] The upper limit for model memory usage, checked on increasing values. end::model-memory-limit-anomaly-jobs[] tag::model-memory-limit-dfa[] The approximate maximum amount of memory resources that are permitted for analytical processing. The default value for {dfanalytics-jobs} is `1gb`. If your `elasticsearch.yml` file contains an `xpack.ml.max_model_memory_limit` setting, an error occurs when you try to create {dfanalytics-jobs} that have `model_memory_limit` values greater than that setting. For more information, see <>. end::model-memory-limit-dfa[] tag::model-memory-status[] The status of the mathematical models, which can have one of the following values: + -- * `ok`: The models stayed below the configured value. * `soft_limit`: The models used more than 60% of the configured memory limit and older unused models will be pruned to free up space. * `hard_limit`: The models used more space than the configured memory limit. As a result, not all incoming data was processed. -- end::model-memory-status[] tag::model-plot-config[] This advanced configuration option stores model information along with the results. It provides a more detailed view into {anomaly-detect}. + -- WARNING: If you enable model plot it can add considerable overhead to the performance of the system; it is not feasible for jobs with many entities. Model plot provides a simplified and indicative view of the model and its bounds. It does not display complex features such as multivariate correlations or multimodal data. As such, anomalies may occasionally be reported which cannot be seen in the model plot. Model plot config can be configured when the job is created or updated later. It must be disabled if performance issues are experienced. -- end::model-plot-config[] tag::model-plot-config-enabled[] If true, enables calculation and storage of the model bounds for each entity that is being analyzed. By default, this is not enabled. end::model-plot-config-enabled[] tag::model-plot-config-terms[] Limits data collection to this comma separated list of partition or by field values. If terms are not specified or it is an empty string, no filtering is applied. For example, ""CPU,NetworkIn,DiskWrites"". Wildcards are not supported. Only the specified `terms` can be viewed when using the Single Metric Viewer. end::model-plot-config-terms[] tag::model-snapshot-id[] A numerical character string that uniquely identifies the model snapshot. For example, `1575402236000 `. end::model-snapshot-id[] tag::model-snapshot-retention-days[] Advanced configuration option. The period of time (in days) that model snapshots are retained. Age is calculated relative to the timestamp of the newest model snapshot. The default value is `1`, which means snapshots that are one day (twenty-four hours) older than the newest snapshot are deleted. end::model-snapshot-retention-days[] tag::model-timestamp[] The timestamp of the last record when the model stats were gathered. end::model-timestamp[] tag::multivariate-by-fields[] This functionality is reserved for internal use. It is not supported for use in customer environments and is not subject to the support SLA of official GA features. + -- If set to `true`, the analysis will automatically find correlations between metrics for a given `by` field value and report anomalies when those correlations cease to hold. For example, suppose CPU and memory usage on host A is usually highly correlated with the same metrics on host B. Perhaps this correlation occurs because they are running a load-balanced application. If you enable this property, then anomalies will be reported when, for example, CPU usage on host A is high and the value of CPU usage on host B is low. That is to say, you'll see an anomaly when the CPU of host A is unusual given the CPU of host B. NOTE: To use the `multivariate_by_fields` property, you must also specify `by_field_name` in your detector. -- end::multivariate-by-fields[] tag::n-neighbors[] Defines the value for how many nearest neighbors each method of {oldetection} will use to calculate its {olscore}. When the value is not set, different values will be used for different ensemble members. This helps improve diversity in the ensemble. Therefore, only override this if you are confident that the value you choose is appropriate for the data set. end::n-neighbors[] tag::node-address[] The network address of the node. end::node-address[] tag::node-datafeeds[] For started {dfeeds} only, this information pertains to the node upon which the {dfeed} is started. end::node-datafeeds[] tag::node-ephemeral-id[] The ephemeral ID of the node. end::node-ephemeral-id[] tag::node-id[] The unique identifier of the node. end::node-id[] tag::node-jobs[] Contains properties for the node that runs the job. This information is available only for open jobs. end::node-jobs[] tag::num-top-classes[] Defines the number of categories for which the predicted probabilities are reported. It must be non-negative. If it is greater than the total number of categories (in the {version} version of the {stack}, it's two) to predict then we will report all category probabilities. Defaults to 2. end::num-top-classes[] tag::open-time[] For open jobs only, the elapsed time for which the job has been open. end::open-time[] tag::out-of-order-timestamp-count[] The number of input documents that are out of time sequence and outside of the latency window. This information is applicable only when you provide data to the {anomaly-job} by using the <>. These out of order documents are discarded, since jobs require time series data to be in ascending chronological order. end::out-of-order-timestamp-count[] tag::outlier-fraction[] Sets the proportion of the data set that is assumed to be outlying prior to {oldetection}. For example, 0.05 means it is assumed that 5% of values are real outliers and 95% are inliers. end::outlier-fraction[] tag::over-field-name[] The field used to split the data. In particular, this property is used for analyzing the splits with respect to the history of all splits. It is used for finding unusual values in the population of all splits. For more information, see {ml-docs}/ml-configuring-pop.html[Performing population analysis]. end::over-field-name[] tag::partition-field-name[] The field used to segment the analysis. When you use this property, you have completely independent baselines for each value of this field. end::partition-field-name[] tag::prediction-field-name[] Defines the name of the prediction field in the results. Defaults to `_prediction`. end::prediction-field-name[] tag::processed-field-count[] The total number of fields in all the documents that have been processed by the {anomaly-job}. Only fields that are specified in the detector configuration object contribute to this count. The timestamp is not included in this count. end::processed-field-count[] tag::processed-record-count[] The number of input documents that have been processed by the {anomaly-job}. This value includes documents with missing fields, since they are nonetheless analyzed. If you use {dfeeds} and have aggregations in your search query, the `processed_record_count` is the number of aggregation results processed, not the number of {es} documents. end::processed-record-count[] tag::randomize-seed[] Defines the seed to the random generator that is used to pick which documents will be used for training. By default it is randomly generated. Set it to a specific value to ensure the same documents are used for training assuming other related parameters (for example, `source`, `analyzed_fields`, etc.) are the same. end::randomize-seed[] tag::query[] The {es} query domain-specific language (DSL). This value corresponds to the query object in an {es} search POST body. All the options that are supported by {es} can be used, as this object is passed verbatim to {es}. By default, this property has the following value: `{""match_all"": {""boost"": 1}}`. end::query[] tag::query-delay[] The number of seconds behind real time that data is queried. For example, if data from 10:04 a.m. might not be searchable in {es} until 10:06 a.m., set this property to 120 seconds. The default value is randomly selected between `60s` and `120s`. This randomness improves the query performance when there are multiple jobs running on the same node. For more information, see {ml-docs}/ml-delayed-data-detection.html[Handling delayed data]. end::query-delay[] tag::rare-category-count[] The number of categories that match just one categorized document. end::rare-category-count[] tag::renormalization-window-days[] Advanced configuration option. The period over which adjustments to the score are applied, as new data is seen. The default value is the longer of 30 days or 100 `bucket_spans`. end::renormalization-window-days[] tag::results-index-name[] A text string that affects the name of the {ml} results index. The default value is `shared`, which generates an index named `.ml-anomalies-shared`. end::results-index-name[] tag::results-retention-days[] Advanced configuration option. The period of time (in days) that results are retained. Age is calculated relative to the timestamp of the latest bucket result. If this property has a non-null value, once per day at 00:30 (server time), results that are the specified number of days older than the latest bucket result are deleted from {es}. The default value is null, which means all results are retained. end::results-retention-days[] tag::retain[] If `true`, this snapshot will not be deleted during automatic cleanup of snapshots older than `model_snapshot_retention_days`. However, this snapshot will be deleted when the job is deleted. The default value is `false`. end::retain[] tag::script-fields[] Specifies scripts that evaluate custom expressions and returns script fields to the {dfeed}. The detector configuration objects in a job can contain functions that use these script fields. For more information, see {ml-docs}/ml-configuring-transform.html[Transforming data with script fields] and <>. end::script-fields[] tag::scroll-size[] The `size` parameter that is used in {es} searches. The default value is `1000`. end::scroll-size[] tag::search-bucket-avg[] The average search time per bucket, in milliseconds. end::search-bucket-avg[] tag::search-count[] The number of searches run by the {dfeed}. end::search-count[] tag::search-exp-avg-hour[] The exponential average search time per hour, in milliseconds. end::search-exp-avg-hour[] tag::search-time[] The total time the {dfeed} spent searching, in milliseconds. end::search-time[] tag::size[] Specifies the maximum number of {dfanalytics-jobs} to obtain. The default value is `100`. end::size[] tag::snapshot-id[] Identifier for the model snapshot. end::snapshot-id[] tag::source-put-dfa[] The configuration of how to source the analysis data. It requires an `index`. Optionally, `query` and `_source` may be specified. + .Properties of `source` [%collapsible%open] ==== `index`::: (Required, string or array) Index or indices on which to perform the analysis. It can be a single index or index pattern as well as an array of indices or patterns. + WARNING: If your source indices contain documents with the same IDs, only the document that is indexed last appears in the destination index. `query`::: (Optional, object) The {es} query domain-specific language (<>). This value corresponds to the query object in an {es} search POST body. All the options that are supported by {es} can be used, as this object is passed verbatim to {es}. By default, this property has the following value: `{""match_all"": {}}`. `_source`::: (Optional, object) Specify `includes` and/or `excludes` patterns to select which fields will be present in the destination. Fields that are excluded cannot be included in the analysis. + .Properties of `_source` [%collapsible%open] ===== `includes`:::: (array) An array of strings that defines the fields that will be included in the destination. `excludes`:::: (array) An array of strings that defines the fields that will be excluded from the destination. ===== ==== end::source-put-dfa[] tag::sparse-bucket-count[] The number of buckets that contained few data points compared to the expected number of data points. If your data contains many sparse buckets, consider using a longer `bucket_span`. end::sparse-bucket-count[] tag::standardization-enabled[] If `true`, then the following operation is performed on the columns before computing outlier scores: (x_i - mean(x_i)) / sd(x_i). Defaults to `true`. For more information, see https://en.wikipedia.org/wiki/Feature_scaling#Standardization_(Z-score_Normalization)[this wiki page about standardization]. end::standardization-enabled[] tag::state-anomaly-job[] The status of the {anomaly-job}, which can be one of the following values: + -- * `closed`: The job finished successfully with its model state persisted. The job must be opened before it can accept further data. * `closing`: The job close action is in progress and has not yet completed. A closing job cannot accept further data. * `failed`: The job did not finish successfully due to an error. This situation can occur due to invalid input data, a fatal error occurring during the analysis, or an external interaction such as the process being killed by the Linux out of memory (OOM) killer. If the job had irrevocably failed, it must be force closed and then deleted. If the {dfeed} can be corrected, the job can be closed and then re-opened. * `opened`: The job is available to receive and process data. * `opening`: The job open action is in progress and has not yet completed. -- end::state-anomaly-job[] tag::state-datafeed[] The status of the {dfeed}, which can be one of the following values: + -- * `starting`: The {dfeed} has been requested to start but has not yet started. * `started`: The {dfeed} is actively receiving data. * `stopping`: The {dfeed} has been requested to stop gracefully and is completing its final action. * `stopped`: The {dfeed} is stopped and will not receive data until it is re-started. -- end::state-datafeed[] tag::summary-count-field-name[] If this property is specified, the data that is fed to the job is expected to be pre-summarized. This property value is the name of the field that contains the count of raw data points that have been summarized. The same `summary_count_field_name` applies to all detectors in the job. + -- NOTE: The `summary_count_field_name` property cannot be used with the `metric` function. -- end::summary-count-field-name[] tag::tags[] A comma delimited string of tags. A {infer} model can have many tags, or none. When supplied, only {infer} models that contain all the supplied tags are returned. end::tags[] tag::timeout-start[] Controls the amount of time to wait until the {dfanalytics-job} starts. Defaults to 20 seconds. end::timeout-start[] tag::timeout-stop[] Controls the amount of time to wait until the {dfanalytics-job} stops. Defaults to 20 seconds. end::timeout-stop[] tag::time-format[] The time format, which can be `epoch`, `epoch_ms`, or a custom pattern. The default value is `epoch`, which refers to UNIX or Epoch time (the number of seconds since 1 Jan 1970). The value `epoch_ms` indicates that time is measured in milliseconds since the epoch. The `epoch` and `epoch_ms` time formats accept either integer or real values. + + NOTE: Custom patterns must conform to the Java `DateTimeFormatter` class. When you use date-time formatting patterns, it is recommended that you provide the full date, time and time zone. For example: `yyyy-MM-dd'T'HH:mm:ssX`. If the pattern that you specify is not sufficient to produce a complete timestamp, job creation fails. end::time-format[] tag::time-span[] The time span that each search will be querying. This setting is only applicable when the mode is set to `manual`. For example: `3h`. end::time-span[] tag::timestamp-results[] The start time of the bucket for which these results were calculated. end::timestamp-results[] tag::tokenizer[] The name or definition of the <> to use after character filters are applied. This property is compulsory if `categorization_analyzer` is specified as an object. Machine learning provides a tokenizer called `ml_classic` that tokenizes in the same way as the non-customizable tokenizer in older versions of the product. If you want to use that tokenizer but change the character or token filters, specify `""tokenizer"": ""ml_classic""` in your `categorization_analyzer`. end::tokenizer[] tag::total-by-field-count[] The number of `by` field values that were analyzed by the models. This value is cumulative for all detectors in the job. end::total-by-field-count[] tag::total-category-count[] The number of categories created by categorization. end::total-category-count[] tag::total-over-field-count[] The number of `over` field values that were analyzed by the models. This value is cumulative for all detectors in the job. end::total-over-field-count[] tag::total-partition-field-count[] The number of `partition` field values that were analyzed by the models. This value is cumulative for all detectors in the job. end::total-partition-field-count[] tag::trained-model-configs[] An array of trained model resources, which are sorted by the `model_id` value in ascending order. + .Properties of trained model resources [%collapsible%open] ==== `created_by`::: (string) Information on the creator of the trained model. `create_time`::: (<>) The time when the trained model was created. `default_field_map` ::: (object) A string to string object that contains the default field map to use when inferring against the model. For example, data frame analytics may train the model on a specific multi-field `foo.keyword`. The analytics job would then supply a default field map entry for `""foo"" : ""foo.keyword""`. + Any field map described in the inference configuration takes precedence. `estimated_heap_memory_usage_bytes`::: (integer) The estimated heap usage in bytes to keep the trained model in memory. `estimated_operations`::: (integer) The estimated number of operations to use the trained model. `license_level`::: (string) The license level of the trained model. `metadata`::: (object) An object containing metadata about the trained model. For example, models created by {dfanalytics} contain `analysis_config` and `input` objects. `model_id`::: (string) Idetifier for the trained model. `tags`::: (string) A comma delimited string of tags. A {infer} model can have many tags, or none. `version`::: (string) The {es} version number in which the trained model was created. ==== end::trained-model-configs[] tag::training-percent[] Defines what percentage of the eligible documents that will be used for training. Documents that are ignored by the analysis (for example those that contain arrays with more than one value) won’t be included in the calculation for used percentage. Defaults to `100`. end::training-percent[] tag::use-null[] Defines whether a new series is used as the null series when there is no value for the by or partition fields. The default value is `false`. end::use-null[] ",16140,True,3281.3209682852475,median "= Modeling Process Logic :author: Alphora :doctype: book :data-uri: :lang: en :encoding: iso-8859-1 [[DDGModelingProcessLogic]] == Summary In addition to being a relationally complete data manipulation language, D4 provides a full imperative language for modeling the process logic of a given application. This chapter discusses the various imperative features of the D4 language such as flow control, structured exception handling, and operators. Note that although this chapter focuses on the imperative features of the D4 language, the Dataphor platform is a declarative development environment. In a traditional imperative language, the product of application development is an executable containing a ""main"" program loop. By contrast, the product of development in Dataphor is a set of application schema that model the problem domain, adorned with pieces of imperative code that run in response to events throughout the system, more like the _event-driven programming_ model of RAD paradigms. [[DDGModelingProcessLogic-LanguageElements]] == Language Elements As with any imperative language, the basic elements of the D4 language are types, values, variables, statements, expressions, and operators. Types have already been discussed in some detail, and so we simply repeat the definition here for completeness: types are named sets of values. Each type allows the developer to specify the valid domain of values for a given context within the language such as a variable, a column within a table, or the parameters of an operator. Every value, such as the integer value 5, has an associated type. The type of a given value is fixed by the compiler, and is used to guarantee at compile-time that every usage of the value within the language is valid within the context in which it appears. This is commonly referred to as __strong-typing__, and allows the compiler to verify the semantics, or meaning, of a given program. Variables provide the storage locations for values within the D4 language. Variables can be as simple as a local variable of type Integer, and as complex as a base table variable within the global database. Every variable has a _scope_ which defines the lifetime and accessibility of the variable. Variables declared within local scopes, such as those delimited by **begin**..*end* blocks within D4, are valid only within that scope, or a nested scope. In addition, table variables can be defined within the global scope, or database, and also within the scope of the current session, by using the keyword *session* in the *create table* or *view* statement. Statements form the fundamental unit of execution within the D4 language. Various statements are provided for performing basic tasks within the language such as variable declaration, structural definition, and so on. There are three basic categories of statements within D4: imperative statements, data manipulation language statements, and data definition language statements. Imperative statements are the basic statements such as assignment and flow control statements that form the basis of the imperative capabilities of the D4 language. These statements will be discussed in more detail in the following sections. Data manipulation language statements are the familiar **select**, **insert**, **update**, and *delete* statements that are used to retrieve and manipulate data in table variables. Data definition language statements are used to describe and maintain the various catalog structures available within D4. These are statements such as *create table* and **create operator**. Expressions are statements that return a value. Expressions can be as simple as a single literal value selector, or as complex as an arbitrary table-valued expression. An important point to be made is that any given expression in D4 can be combined with other expressions to produce larger expressions. These can then be further combined with other expressions and so on, allowing expressions of arbitrary complexity to be built within the language. This may seem like a trivial observation, but the degree to which this nesting of expressions is possible within a language has a direct impact on its flexibility and power. Traditionally, DBMS languages such as SQL have suffered from various limitations on the types of expressions that can appear in given contexts. One of the goals of the Dataphor Server is to insulate the developer as much as possible from these limitations in existing systems. Operators are pre-compiled sets of D4 statements that can be invoked from elsewhere within a D4 program. Each operator can take any number of parameters, each with a name and declared type, and can optionally return a value of some type. If a given operator does not return a value, it is considered a statement equivalent, and can be used anywhere that a statement is expected within D4. If an operator does return a value, it is considered an expression equivalent, and can be used anywhere that an expression is expected, so long as the return type of the operator is valid within the context in which it appears, of course. These basic elements provide the foundation for all the functionality and capabilities of the D4 language. The following sections discuss the various imperative statements and capabilities of the D4 language in more detail. The chapter concludes with an example of processing logic taken from the Shipping application. [[DDGModelingProcessLogic-ValuesandVariables]] == Values and Variables In addition to the scalar types discussed in the <> chapter, the D4 language provides the following categories of types: * Lists * Rows * Tables * Cursors Each of these type categories can be used to declare variables, select and manipulate values, and define operator parameters and result types. The following sections will discuss each of these types of values. [[DDGModelingProcessLogic-ValuesandVariables-UsingLists]] === Using Lists This section describes how to use list selectors and the system-provided operators of the Dataphor Server to construct and manipulate list values. A list is an ordered collection of values of the same type. Values in the list are distinguishable by ordinal position. The list type specifies the type of values in the list. A list selector is used to construct a list value: .... begin var LList : list(Integer) := { 12, 13, 14, 15 }; // list type can be specified in the selector LList := list(Integer) { }; end; .... The following operators are defined for lists: Comparison Operators:: The comparison operators link:O-System.iEqual.html[=] and link:O-System.iNotEqual.html[<>] are defined for list values. Two lists are equal if they are of the same type, have the same number of values, and the values in each list are equal by ordinal position: + .... begin var LList1 := { 1, 2, 3 }; var LList2 := { 1, 2, 3 }; if not(LList1 = LList2) then raise Error(""Lists not equal""); end; .... Membership Operator:: The membership operator *link:O-System.iIn.html[in]* is defined for lists and returns true if the given value is in the specified list: + .... begin var LList := { 1, 2, 3 }; if not(3 in LList) then raise Error(""3 is not in the list""); end; .... List Indexer:: The indexer operator (link:O-System.iIndexer.html[[]]) is defined for lists and allows the values of a list to be accessed by ordinal position within the list. Indexes are zero-based: + .... begin var LList := { 1, 2, 3 }; if not(LList[0] = 1) then raise Error(""First item is not 1""); end; .... link:O-System.Count.html[Count]:: Returns the number of values in the given list. link:O-System.Clear.html[Clear]:: Removes all values from the specified list. The target list must be a list variable. link:O-System.iExtend.html[Add]:: Adds the specified value into the given list. The target list must be a list variable. link:O-System.Insert.html[Insert]:: Inserts the specified value in the given list at the desired location. The target list must be a list variable. link:O-System.iRemove.html[Remove]:: Removes the specified value from the given list. The target list must be a list variable. link:O-System.RemoveAt.html[RemoveAt]:: Removes the value at the specified location from the given list. The target list must be a list variable. link:O-System.IndexOf.html[IndexOf]:: Returns the index of the specified value within the given list. If the value is not in the list, -1 is returned. For more information on these operators, refer to link:O-System.ListOperators.html[List Operators]. [[DDGModelingProcessLogic-ValuesandVariables-UsingRows]] === Using Rows This section describes how to use row selectors and the system-provided operators of the Dataphor Server to construct and manipulate <>. A row is a set of named values called columns. The row type specifies the name and type of each column. A row selector is used to construct a value of a specified row type: .... var LRow : row { ID : Integer } := row { 5 ID }; .... As the preceding example illustrates, variables are allowed to be of any <>. Optionally, the type of the row can be specified as part of the row selector. In this case, the expressions in the row selector provide values for the columns of the row. For example, to define a row with nil for all columns, use a type specifier in the selector, but do not provide any expressions in the body of the selector: .... var LRow := row of { ID : Integer } { }; .... When combined with the *typeof* type specifier, this can provide a useful shorthand. For example, within the body of a row-valued operator, the *result* can be initialized with an empty row with the following statement: .... result := row of typeof(result) { }; .... The following operators are defined for row types: Comparison Operators:: The comparison operators link:O-System.iEqual.html[=] and link:O-System.iNotEqual.html[<>] are defined for row values. Two row values are equal if they are of the same row type and both rows have values for the same set of columns by name, and those values are equal. Column Extractor:: The column extraction operator . (dot) retrieves the value for a single column in the row. If the row does not have a value for the given column, the result is nil. If the row variable that is the target of the extraction does not have a value, the result of evaluating the extraction is also nil. Row Update:: Row <> allows the values for specific columns within a given row to be changed. The target of a row update must be a variable: + .... begin var LRow := row { 5 ID, ""John"" Name }; update LRow set { Name := ""Jack"" }; end; .... Row Project:: Row project (**link:O-System.iProject.html[over]**) returns a row with only the specified columns of the given row: + .... begin var LRow1 := row { 5 ID, ""John"" Name }; var LRow2 := LRow1 over { ID }; end; .... Row Remove:: Row *link:O-System.iRemove.html[remove]* returns a row with the specified columns removed from the given row: + .... begin var LRow1 := row { 5 ID, ""John"" Name }; var LRow2 := LRow1 remove { Name }; end; .... Row Add:: Row *link:O-System.iExtend.html[add]* allows columns to be added to a given row. The current values of the columns in the source row are available by column name within the expressions defining the new columns: + .... begin var LRow1 := row { 5 ID }; var LRow2 := LRow1 add { ""John"" Name }; end; .... Row Redefine:: Row <> allows columns of a given row to be redefined. The current values of the columns in the source row are available by column name within the expressions defining the new columns. Just as with table redefine, this operator is defined as a shorthand for adding a new column X, removing some column Y, and then renaming X to Y: + .... begin var LRow1 := row { 5 ID, ""John"" Name }; LRow1 := LRow1 redefine { ID := 6 }; // equivalent LRow1 := LRow1 add { 6 X } remove { ID } rename { X ID }; end; .... Row Rename:: Row *link:O-System.iRename.html[rename]* allows columns of a given row to be renamed. The values of the renamed columns are unaffected: + .... begin var LRow1 := row { 5 ID, ""John"" Name }; var LRow2 := LRow1 rename { ID X, Name Y }; end; .... Row Specify:: Row specify allows the desired columns to be specified. Just as for table-valued expressions, this operator is shorthand for an extend-project-rename operation. Row Join:: Row *link:O-System.iJoin.html[join]* allows two rows to be joined together. If the two rows have common column names, the values for those columns in each row must be equal: + .... begin var LRow1 := row { 5 ID, ""John"" Name }; var LRow2 := row { 5 ID, ""Provo"" City }; var LRow3 := row { 6 ID, ""Orem"" City }; var LRow4 : row { ID : Integer, Name : String, City : String }; LRow4 := LRow1 join LRow2; LRow4 := LRow1 join LRow3; // this is an error end; .... [[DDGModelingProcessLogic-ValuesandVariables-UsingTables]] === Using Table Values In addition to global and session-specific table variables, D4 allows table types to be used in local table variable declarations, as well as parameter types. This section discusses the usage of table variables and values within the imperative context of the D4 language. Table values are sets of rows, each of the same type. A table type specifier is used to specify the names and types of each column in the table value. Table selectors are used to construct table values: .... begin var LTable : table { ID : Integer }; LTable := table { row { 1 ID }, row { 1 } }; end; .... Note that a table selector is simply a comma-delimited list of row-valued expressions, of which row selectors are just one variety. In other words, a table selector need not be constructed entirely from row selectors. For example: .... insert table { RowValuedOperator(), LTable[1] } into LTable2; .... In addition, table selectors are simply another variety of table-valued expression, and can be used anywhere a table-value is required. As with all variable declaration statements, the type specifier is optional if an initializer is provided: .... var LTable := table { row { 1 ID } }; .... When a type specifier is not given as part of a variable declaration statement, the compiler infers the type of the variable based on the type of the initializer expression. The various operators that can be performed on table values have already been discussed in detail in <>. As mentioned previously, D4 also allows for the definition of local table variables, and for parameters and return values to be table-typed. There are several points to be made regarding this functionality. Chunking BoundaryFirst, local table variables are allocated within the query processor directly, rather than as part of a device. As such, they constitute a __chunking boundary__, or a point at which the distributed query mechanisms of the query processor must take over. Because data must be transferred into the query processor whenever a chunking boundary is crossed, care should be taken to avoid excessive data copying. Second, local table variables exhibit the same copy semantics that non-table variables do. They are values just like the integer value 5, and while the query processor is optimized to perform only the processing that is necessary, the results of a local table variable assignment will be materialized fully. Third, the mechanism for declaring local table variables does not allow for the definition of the other structural information associated with global and session-specific table variables. The only structural information that can be provided for local table variables is the heading information, or the names and types of each column in the table value. Specifically, keys, orders, metadata, constraints, references, etc.,. cannot be provided for local table variables footnote:[This is a byproduct of the syntax of the table type specifier in D4. Although it is strictly correct that the type specifier only specify the type (keys, constraints, and other structural information are part of the variable definition rather than the type definition) it has the unfortunate side effect of limiting the functionality of local table variables. We plan on addressing this problem in a future release of the product.]. And finally, table operators in D4 are fully __pipelined__. This means that whenever possible, table operators evaluate a row-at-a-time as data is requested. User-defined table-valued operators, while allowed, cannot be optimized in this way if they are written in D4 footnote:[Although the details of this behavior are beyond the scope of this discussion, it suffices to say that the internal representation of the table value is different for pipelined execution, and that only host-implemented operators can access the pipelined representation of a table value.]. As a result, D4 implemented table-valued operators cannot be pipelined, and the results of the entire operation will be materialized on every invocation. [[DDGModelingProcessLogic-ValuesandVariables-UsingCursors]] === Using Cursors This section describes the general usage of cursors in D4. Many of the operations dealing with cursors are operators in the System Library. These operators will be covered briefly. For a complete description of each operator, refer to link:O-System.CursorOperators.html[Cursor Operators]. Cursors in the Dataphor Server allow navigational access to the results of a given table expression. A _cursor selector_ is used to declare and open a cursor. Declaring a cursor allocates server resources which must be released. This is done using the link:O-System.Close.html[Close] operator. Note that the resource protection block (**try**..**finally**) should always be used to ensure that a cursor is closed. Cursors in the Dataphor Server are ""cracked"", meaning that the cursor can be positioned before the first row (BOF), after the last row (EOF), or on some row. It is an error to attempt a read or update operation against a cursor that is positioned on a crack. The link:O-System.BOF.html[BOF] and link:O-System.EOF.html[EOF] operators return true if the cursor is positioned on the BOF or EOF crack, respectively. If both BOF and EOF are true, the cursor is ranging over an empty set. The functionality of a cursor is divided up into __capabilities__. Capabilities are requested as part of the cursor definition. For a complete description of <> and other cursor behaviors, refer to the D4 Language Guide discussion of the <>. Once a cursor is open, all operations against it are done using the cursor operators: link:O-System.Select.html[Select]:: Select(**const** ACursor : **cursor**) : *row* + Select(**const** ACursor : **cursor**, *var* ARow : **row**) + Selects the current row from the cursor specified by ACursor. It is an error to call Select if either BOF or EOF is true. + If no row is provided, the Select operator returns a row. Otherwise, the values of the given row will be set to the values of the current row in the cursor. + The row specified by ARow need not conform to the heading for the table over which the cursor ranges. Columns are matched by name with the given row. link:O-System.Insert.html[Insert]:: Insert(**const** ACursor : **cursor**, *const* ARow : **row**) + Inserts the row given by ARow into the cursor specified by ACursor. The position of the cursor after the insert is determined by the cursor type specified in the cursor definition. If the cursor is static, the newly inserted row will not be visible in the cursor and the position of the cursor is unaffected. If the cursor is dynamic, the newly inserted row will be visible, and the cursor will attempt to be positioned on the new row. If the cursor is searchable, the cursor will be positioned on the newly inserted row, otherwise, it will be positioned as though link:O-System.Reset.html[Reset] had been called. + The row specified by ARow need not conform to the heading for the table over which the cursor ranges. Columns are matched by name with the given row. link:O-System.Update.html[Update]:: Update(**const** ACursor : **cursor**, *const* ARow : **row**) + Updates the current row of the cursor specified by ACursor to the values given by ARow. It is an error to call Update if either BOF or EOF is true. The position of the cursor after the update is determined by the cursor type specified in the cursor definition. If the cursor is __static__, the update will not be visible in the cursor and the position of the cursor is unaffected. If the cursor is __dynamic__, the update will be visible, and the cursor will attempt to refresh to the updated row. If the cursor is searchable, the cursor will be positioned on the updated row, otherwise, it will be positioned as though a link:O-System.Reset.html[Reset] had been called. + The row specified by ARow need not conform to the heading for the table over which the cursor ranges. Columns are matched by name with the given row. link:O-System.Delete.html[Delete]:: Delete(**const** ACursor : **cursor**) + Deletes the current row of the cursor specified by ACursor. It is an error to call Delete if either BOF or EOF is true. The position of the cursor after the delete is determined by the cursor type specified in the cursor definition. If the cursor is static, the delete will not be visible in the cursor, and the position of the cursor is unaffected. If the cursor is dynamic, the delete will be visible in the cursor, and the cursor will attempt to be positioned as close as possible to the deleted row. If the cursor is searchable, the cursor will be positioned as though a FindNearest had been called on the deleted row. Otherwise, it will be positioned as though a link:O-System.Reset.html[Reset] had been called. + The row specified by ARow need not conform to the heading for the table over which the cursor ranges. Columns are matched by name with the given row. link:O-System.BOF.html[BOF]:: BOF(**const** ACursor : **cursor**) : Boolean + Returns true if the cursor specified by ACursor is positioned on the BOF crack, or before the first row in the result set, and false otherwise. link:O-System.EOF.html[EOF]:: EOF(**const** ACursor : **cursor**) : Boolean + Returns true if the cursor specified by ACursor is positioned on the EOF crack, or after the last row in the result set, and false otherwise. link:O-System.First.html[First]:: First(**const** ACursor : **cursor**) + Positions the cursor specified by ACursor on the BOF crack. BOF is guaranteed to be true after a call to First. link:O-System.Prior.html[Prior]:: Prior(**const** ACursor : **cursor**) : Boolean + Navigates the cursor specified by ACursor to the prior row in the result set. If the navigation is successful, i.e. the cursor is positioned on a row, the operator returns true. Otherwise, the operator returns false. link:O-System.Next.html[Next]:: Next(**const** ACursor : **cursor**) : Boolean + Navigates the cursor specified by ACursor to the next row in the result set. If the navigation is successful, i.e. the cursor is positioned on a row, the operator returns true. Otherwise, the operator returns false. link:O-System.Last.html[Last]:: Last(**const** ACursor : **cursor**) + Positions the cursor specified by ACursor on the EOF crack. link:O-System.EOF.html[EOF] is guaranteed to be true after a call to Last. link:O-System.Reset.html[Reset]:: Reset(**const** ACursor : **cursor**) + Refreshes the result set for the cursor specified by ACursor from the underlying database and positions the cursor on the BOF crack. Note that even a static cursor will be refreshed after a call to Reset. link:O-System.BOF.html[BOF] is guaranteed to be true after a call to Reset. link:O-System.GetKey.html[GetKey]:: GetKey(**const** ACursor : **cursor**) : *row* + Gets the key value for the current row of the cursor specified by ACursor. This row can be used in subsequent calls to link:O-System.FindKey.html[FindKey] and link:O-System.FindNearest.html[FindNearest]. link:O-System.FindKey.html[FindKey]:: FindKey(**const** ACursor : **cursor**, ARow : **row**) : Boolean + Finds the key value given by ARow in the cursor specified by ACursor. If the find is successful, the operator returns true, indicating that the cursor is positioned on a row with a key value matching that specified by ARow. Otherwise, the operator returns false, and the position of the cursor is unaffected. Note that if the key value specified by ARow is a partial key, then the cursor is not guaranteed to be on any particular row within the set of rows matching the partial key. link:O-System.FindNearest.html[FindNearest]:: FindNearest(**const** ACursor : **cursor**, ARow : **row**) + Finds the row most closely matching the key value given by ARow in the cursor specified by ACursor. No guarantees are made about the position of the cursor after a call to FindNearest. As specified for the FindKey operator, if the key value given by ARow is a partial key, then the cursor is not guaranteed to be on any particular row within the set of rows matching the partial key. link:O-System.Refresh.html[Refresh]:: Refresh(**const** ACursor : **cursor**, ARow : **row**) + Refreshes the result set for the cursor specified by ACursor and attempts to position the cursor on the row given by ARow. This operator is conceptually equivalent to calling link:O-System.Reset.html[Reset] followed by link:O-System.FindNearest.html[FindNearest]. link:O-System.GetBookmark.html[GetBookmark]:: GetBookmark(**const** ACursor : **cursor**) : *row* + Gets a bookmark for the current row of the cursor specified by ACursor. This bookmark can then be used in subsequent calls to link:O-System.GotoBookmark.html[GotoBookmark] and link:O-System.CompareBookmarks.html[CompareBookmarks]. Note that the structure of the row returned by GetBookmark is implementation defined and not guaranteed to be meaningful. A bookmark is only guaranteed to be valid for the cursor from which it was retrieved. link:O-System.GotoBookmark.html[GotoBookmark]:: GotoBookmark(**const** ACursor : **cursor**, *const* ABookmark : **row**) : Boolean + Positions the cursor specified by ACursor on the row corresponding to the bookmark given by ABookmark. This bookmark must have been previously retrieved with a call to link:O-System.GetBookmark.html[GetBookmark]. The operator returns true if the bookmark is valid and the cursor is positioned on the correct row. The operator returns false if the bookmark is invalid, or the row could not be located. If the operator returns false, the position of the cursor is unaffected. link:O-System.CompareBookmarks.html[CompareBookmarks]:: CompareBookmarks(**const** ACursor : **cursor**, *const* ABookmark1 : **row**, *const* ABookmark2 : **row**) : Integer + Compares the bookmarks given by ABookmark1 and ABookmark2 using the cursor specified by ACursor. The given bookmarks must have been previously retrieved with a call to link:O-System.GetBookmark.html[GetBookmark]. The operator returns -1 if ABookmark1 is less than ABookmark2, 0 if they are equal, and 1 if ABookmark1 is greater than ABookmark2. link:O-System.Close.html[Close]:: Close(**const** ACursor : **cursor**) + Closes the cursor specified by ACursor and deallocates any associated resources. All cursors opened using a cursor selector must be closed with this operator. The following examples illustrate the use of cursors in D4: .... // Use a cursor to build a list of names of objects in the system. begin var LCursor : cursor(table { Name : Name }) := cursor(Objects over { Name }); var LNameList : String := """"; try while LCursor.Next() do begin if LNameList.Length() > 0 then LNameList := LNameList + "", ""; LNameList := LNameList + LCursor.Select().Name; end; if LNameList.Length() > 0 then LNameList := LNameList + "".""; raise Error(""Object Names: "" + LNameList); finally LCursor.Close(); end; end; .... .... // Find a specific object name in the system. begin var LCursor : cursor(table { Name : Name }) := cursor ( Objects over { Name } capabilities { Navigable, Searchable } ); try if not LCursor.FindKey(row { Name(""System.Integer"") Name }) then raise Error(""System.Integer data type not found""); finally LCursor.Close(); end; end; .... .... // Find the closest match to a given name in the system begin var LCursor : cursor(table { Name : Name }) := cursor ( Objects over { Name } capabilities { Navigable, Searchable } ); try LCursor.FindNearest(row { Name(""System.FindKey"") Name }); raise Error(LCursor.Select().Name); finally LCursor.Close(); end; end; .... .... // Use bookmarks to reposition the cursor begin var LCursor : cursor(table { Name : Name }) := cursor ( Objects over { Name } capabilities { Navigable, Bookmarkable, Searchable } ); try LCursor.FindKey(row { Name(""System.Integer"") Name }); var LRow : row := LCursor.GetBookmark(); LCursor.First(); LCursor.GotoBookmark(LRow); finally LCursor.Close(); end; end; .... [[DDGModelingProcessLogic-Operators]] == Operators Operators form the fundamental building blocks of any D4 program. Operators can be as simple as the definition of a multiplication operator for some type, or as complex as a payroll calculation or inventory adjustment. Operators can take any number of arguments (including zero) of any type, and can optionally return a value of any type. Note specifically that this includes table and row types. At this point we note that the term _operator_ in D4 applies generally. The language makes no distinction between functions, procedures, operators, subroutines, stored procedures, triggers, etc.,. The built-in addition operator (+) is just as much an operator as the user-defined UpdateInventory(...). Operators that do not return a value may be invoked anywhere that a statement may appear in the D4 language, including in particular the body of other operators. Operators that do return a value may be invoked anywhere that an expression may appear in the D4 language. Operators thus form the basis for abstracting over statements and expressions within D4. D4 operators can be written in D4, or host-implemented. For more information on host-implemented operators, refer to the <> discussion in Implementing Data Types. [[DDGModelingProcessLogic-Operators-OperatorInvocation]] === Operator Invocation Operators in D4 can be invoked in several ways. First, the built-in footnote:[A built-in operator is an operator that is recognized as a symbol of the language e.g. +, rather than as an identifier, e.g. Distance().] operators of the D4 language can be invoked using the parser-recognized symbol: .... 2 + 2 .... Second, an operator can be invoked using its name and passing the required number of arguments: .... Distance(Coordinate(120.12, 87.6), Coordinate(110.13, 87.6)); .... Finally, an operator can be invoked using the dot (.) operator: .... Coordinate(120.12, 87.6).Distance(Coordinate(110.13, 87.6)); .... This last style of invocation allows object-oriented style ""method"" invocation, and is provided as a syntactic convenience. In this style of invocation, the compiler searches for an overload of the operator using the left argument of the dot operator as the first argument. Note that any operator (with at least one parameter) can be invoked in this way. [[DDGModelingProcessLogic-Operators-OperatorPrecedence]] === Operator Precedence Because D4 allows chains of in-fix footnote:[For completeness, the term in-fix refers to the syntactic style of placing the operator symbol between the arguments, e.g. 2 + 2. Note that the term applies mainly to binary built-in operators.] operators, operator precedence must be used to determine the order of operations performed. Of course, order of operation can always be explicitly specified using parentheses. For a complete discussion of operator precedence, refer to <> in the D4 Language Guide. [[DDGModelingProcessLogic-Operators-OperatorResolution]] === Operator Resolution D4 supports operator overloading, meaning that two operators may have the same name as long as they have different signatures. For example, the addition operator (+) in D4 is capable of adding two integers, as well as performing string concatenation. As the following listing shows, the syntax for each expression is the same: .... 1 + 1 ""H"" + ""ello"" .... Because of this, the compiler must be able to determine which overload is being called. This process is called __operator resolution__, and is done by comparing the number and types of the arguments in the invocation with the number and types of the arguments in each overload of the operator being called. During this process, the compiler will make use of implicit conversions in attempting to resolve a particular overload. If the compiler can unambiguously match a single overload signature with the calling signature, the resolution is successful and the appropriate operator is invoked. Otherwise, the compiler will report an error indicating why it was unable to produce a match. For a more in-depth discussion of operator resolution, refer to <> in the D4 Language Guide. [[DDGModelingProcessLogic-Operators-AggregateOperators]] === Aggregate Operators Aggregate operators are D4 operators that are defined with a special calling convention that allows them to be used to compute aggregates of table values. Each aggregate operator has three sections: __initialization__, __aggregation__, and __finalization__. The initialization section is executed one time at the beginning of the computation. The aggregation section is invoked once for each row of the table value being aggregated, with the values for the current row passed as the parameters defined in the signature of the aggregate operator. The finalization section is executed one time at the end of the computation to allow any final steps to be performed. Each of these sections may be written in D4 or host-implemented. Note that variables declared within the initialization section will be visible within the aggregation and finalization sections, but variables declared within the aggregation section will not be visible within the finalization section. In other words, the entire aggregate operator (all three sections inclusive) form a single outer scope, with the aggregation section forming its own nested scope. For a more in-depth discussion of aggregate operators, refer to <> in the D4 Language Guide. [[DDGModelingProcessLogic-FlowControl]] == Flow Control In an imperative language like D4, a program runs as a series of statements that execute sequentially. Each of these statements may be either a built-in D4 statement, or an invocation of some system or user-defined operator. Each operator is itself a series of D4 statements, either built-in, or user-defined. In addition to statements like variable declaration or assignment statements, D4 provides various flow control statements that allow the path of execution within the program to be controlled. D4 provides two main varieties of flow control statements: branching statements, and looping statements. [[DDGModelingProcessLogic-FlowControl-BranchingConstructs]] === Branching Statements Branching statements allow the selection of the next statement to be executed based on the evaluation of some condition. There are two different branching statements in D4: the *if* statement, and the *case* statement. The *if* statement provides a single condition to be evaluated, and determines the next statement to be executed based on the result of evaluating that condition. For example, the following D4 script illustrates the conditional execution of a single statement: .... if exists (Location where ID = '001') then update Location set { Name := 'Location 001' } where ID = '001'; .... The *if* statement also includes an optional *else* clause which allows an alternative statement to be executed. To continue with the previous example: .... if exists (Location where ID = '001') then update Location set { Name := 'Location 001' } where ID = '001' else insert table { row { '001' ID, 'Location 001' Name } } into Location; .... Note that in this example, there is no statement terminator preceding the *else* keyword. This is because the D4 language considers the entire *if..then..else* statement to be a single statement. The *case* statement allows a single statement from among a set of statements to be selected for execution, based on the evaluation of some condition. There are two flavors of the case statement, one in which a single value is tested against multiple values, and one in which multiple conditions are evaluated. Both flavors allow a default condition to be specified using the *else* keyword. The following program listing illustrates both of these statements: .... case LShape when 'Circle' then DrawCircle(); when 'Square' then DrawSquare(); else DrawLine(); end; case when LShape = 'Circle' then DrawCircle(); when LShape = 'Square' then DrawSquare(); else DrawLine(); end; .... Clearly, these two statements are logically equivalent. D4 provides both statements for convenience. [[DDGModelingProcessLogic-FlowControl-LoopingConstructs]] === Looping Statements Looping statements allow a given statement to be executed multiple times. D4 provides five different looping statements: the *for* loop, the *while* loop, the *do..while* loop, the *repeat..until* loop, and a specialized *foreach* statement. The *for* loop allows a given statement to be executed a specified number of times: .... for LIndex : Integer := 1 to 100 do insert table { row { LIndex X } } into Points; .... Note that the *for* loop allows for iterator variable declaration within the statement itself, or referencing an existing variable within the local scope. In addition, the *var* keyword can be used instead of a type specifier as follows: .... for var LIndex := 1 to 100 do insert table { row { LIndex X } } into Points; .... In this case, the type of the variable LIndex is determined by the type of the range expressions. The *while* loop allows a statement to be executed as long as a specified condition remains true: .... begin var LIndex := 1; while LIndex <= 100 do begin insert table { row { LIndex X } } into Points; LIndex := LIndex + 1; end; .... The *do..while* loop introduces a scope within the *do* and *while* keywords, and allows a set of statements to be executed, with the test condition being evaluated after the statements are executed: .... begin var LIndex := 0; do LIndex := LIndex + 1; insert table { row { LIndex X } } into Points; while LIndex < 100; .... The *repeat..until* loop also introduces a scope, and allows a set of statements to be executed _until_ the specified condition evaluates to true: .... begin var LIndex := 1; repeat insert table { row { LIndex X } } into Points; LIndex := LIndex + 1; until LIndex > 100; .... The *foreach* statement is a specialized looping statement that works as a shorthand for an equivalent loop to iterate over the rows in a cursor, or the items in a list: .... begin var LTotal := 0; foreach row in Points do LTotal := LTotal + X; end; .... Note that within the iteration block, the columns of the current row are available by name. Each of these loops can of course be expressed in terms of a simple while loop. D4 allows the various statements for convenience. Within all the loops, the *break* statement may be used to unconditionally terminate the loop in which the break is found, with execution resuming at the first statement immediately following the loop. The *continue* statement may also be used to exit the current iteration; the test condition is evaluated, and execution continues at the first statement in the loop if the condition is satisfied. Note that a *break* or *continue* statement will _not_ skip a finally block. [[DDGModelingProcessLogic-ExceptionHandling]] == Exception Handling Exception handling statements in D4 allow for errors that may occur at runtime to be handled within the program itself. D4 provides two different exception handling statements: the *try..except* statement, and the *try..finally* statement. Structured exception handling provides a vastly superior mechanism for handling error conditions within imperative programs. Without exception handling, the developer of an operator must provide some mechanism to indicate to the caller that an error condition has occurred. It is then up to the caller to check the return code of each invocation of an operator, resulting in large amounts of error-handling code for even the most trivial of operations. In contrast, structured exception handling allows the user of a particular operator to develop optimistically. In other words, code can be written assuming everything will work. If necessary, an error handling block can be introduced surrounding the code in question to handle any error conditions without affecting the regular program logic. Exception handling in D4 makes use of the system Error type to provide information about exceptions that occur within D4. The following program listing shows the definition of this type: .... // System.Error create type Error { representation Error { Severity : String, Code : Integer, Message : String, InnerError : Error } }; .... Each error value in D4 has a Severity, a Code, a Message, and an InnerError. The severity value for an error is one of User, Application, Environment, or System, and indicates the relative severity of the error. Each error is also assigned a code, which is a six-digit number representing both the source module of the error, as well as the specific code of the error. The first three digits correspond to the source module, such as the server subsystem, or the schema subsystem. For a complete list of these module codes, refer to the Error Code Source Reference.. Application defined error codes should always be between 500000 and 999999. The message for an error value contains the descriptive text of the exception that occurred, and the InnerError component provides access to another Error value that can be used to nest errors as they occur. Note that the InnerError component of an Error will be *nil* if no inner error is available. The *raise* statement is used to throw an exception from a D4 program. There are two contexts in which a *raise* can appear. First, as a raise statement, the keyword is used to raise an error directly, and must be followed by an expression of type Error. This is most often an invocation of the Error selector, but does not have to be. Second, within an exception handler, the *raise* keyword can be used stand-alone to re-raise the exception being handled. [[DDGModelingProcessLogic-ExceptionHandling-Try..Except]] === Try..Except The *try..except* statement is used to execute a set of statements, and optionally handle any exception that is raised within those statements. The *except* clause can be used in two different ways. First, as a generic exception handler that traps any exception occurring. The keyword *raise* can be used within the exception handler portion of the statement to re-throw the exception: .... try insert table { row { '001' ID, 'Location 001' Name } } into Location; except update Location set { Name := 'Location 001' } where ID = '001'; raise; end; .... Second, the *except* clause may specify a parameterized handler so that the exception that occurred can be inspected within the exception handler: .... try insert table { row { '001' ID, 'Location 001' Name } } into Location; except on E : Error do begin if E.Severity = 'User' then update Location set { Name := 'Location 001' } where ID = '001' else raise E; end; end; .... [[DDGModelingProcessLogic-ExceptionHandling-Try..Finally]] === Try..Finally The *try..finally* statement is used to protect a given resource, ensuring that a specific block of statements will be executed regardless of whether an exception is raised or not. Because this statement is most often used to protect resources, it is often called a __resource protection block__. The following example depicts the use of a *try..finally* statement: .... begin var LCursor := cursor(BaseTableVars { Name }); try ... finally LCursor.Close(); end; end; .... [[DDGModelingProcessLogic-TransactionManagement]] == Transaction Management As with any DBMS, the Dataphor Server must provide transaction management services to allow applications to guarantee the integrity and consistency of operations, especially in the presence of concurrent access, and system failures. To enable these capabilities, the Dataphor Server exposes two different kinds of transaction management services: first, traditional two-phase commit transaction management, and second, application transactions. For a complete discussion of transaction management issues, refer to <> in Part I of this guide. [[DDGModelingProcessLogic-TransactionManagement-TransactionManagementServices]] === Transaction Management Services The Dataphor Server exposes basic transaction management services primarily through the Call-Level Interface, but the services are also available within the D4 language by calling transaction management operators. The following list details the available transaction management operators: BeginTransaction():: Begins a transaction on the current process at the default isolation level for the process. BeginTransaction(const AIsolationLevel : String):: Begins a transaction on the current process at the specified isolation level. PrepareTransaction():: Prepares the current transaction for commit by checking all deferred integrity constraints and invoking all deferred event handlers. This call will be invoked internally if not called prior to transaction commit. It is only exposed to allow the Dataphor Server to participate in two-phase commit distributed transactions. CommitTransaction():: Prepares the current transaction if necessary, and commits it. * RollbackTransaction() + Rolls back the current transaction, undoing any data modifications that were performed during the transaction. InTransaction():: Indicates whether or not the current process is participating in any transactions. TransactionCount():: Returns the number of transactions currently active on the current process. After calling BeginTransaction(), the number of active transactions on the current process is increased by one. If a transaction is already in progress on the current process, this transaction is a __nested transaction__. Transactions can be nested to any degree, even if the target systems with which the Dataphor Server is communicating do not support nested transactions. In this case, the Dataphor Server will take over logging the nested transactions, while still taking advantage of the transaction management capabilities of the target system for the outer most transaction. After calling CommitTransaction() or RollbackTransaction(), the number of active transactions on the current process is decreased by one. Note that the scope of each transaction is the current process, and that, in general, multiple processes may be running for a single session. In addition to explicit transaction management, the Dataphor Server will implicitly manage transaction for calls crossing the CLI boundary. This is called Transactional Call Protocol, and effectively ensures that any call into the Dataphor Server is protected by a transaction. If the call succeeds, the implicit transaction is committed. If an error occurs, the implicit transaction is rolled back, and the error is returned to the caller. This behavior can be controlled with the UseImplicitTransactions setting either through the CLI, or by updating the System.Processes table directly. Because the Dataphor Server may be communicating with multiple devices on behalf of the current process, each of these devices must be enlisted in the transaction. This is called a _distributed transaction_ and is either coordinated by the Dataphor Server, or managed by the Microsoft Distributed Transaction Coordinator, depending on the value of the UseDTC setting for the current process. This setting may be changed through the CLI, or by updating the System.Processes table directly. Because transaction management is such an integral part of any application, the D4 language provides the *try..commit* statement as a convenient shorthand for protecting operations with transactions and structured exception handling. The following example depicts a typical use of this statement: .... try ProcessInvoices(); commit; .... This statement is equivalent to the following sequence of statements: .... begin BeginTransaction(); try ProcessInvoices(); CommitTransaction(); except RollbackTransaction(); raise; end; end; .... [[DDGModelingProcessLogic-TransactionManagement-ApplicationTransactionManagement]] === Application Transaction Management In addition to traditional transaction management, the Dataphor Server exposes an application-targeted capability called __application transactions__. Essentially, these are long-running, optimistically concurrent transactions that are used by Dataphor Frontend Clients to enable data entry in the presence of the business rules being enforced on the server. For a complete discussion of application transactions, refer to <> in the Presentation Layer part of this guide. [[DDGModelingProcessLogic-Characteristics]] == Characteristics Every expression and operator within the D4 language has various characteristics that are inferred by the compiler. These characteristics govern the contexts in which a given expression or operator may be used, and help the optimizer perform expression transformations and make distributed query processing decisions. The following list itemizes these characteristics: * Literal * Remotable * Functional * Deterministic * Repeatable * Nilable * Context Literal * Order Preserving The following sections discuss each of these characteristics in detail. [[DDGModelingProcessLogic-Characteristics-Literal]] === Literal Broadly speaking, a literal expression in D4 is one that can be evaluated at compile-time with the same results as an evaluation at run-time. For example, the integer literal 5 will always result in the integer value 5. Clearly, any expression that references a variable, regardless of scope, is not literal. An operator is considered literal if it makes no reference to global state. An operator invocation is literal if the operator is literal and all the arguments to the operator are literal. Of course, this definition applies recursively, meaning that literal expressions are allowed to be arbitrarily complex, so long as they do not reference any variables. Note that a local variable reference within an operator does not mean the operator is not literal, only a global variable reference will make an operator non-literal. For example, the following operator is literal: .... create operator LiteralOperator(const AInteger : Integer) : Integer begin var LValue := AInteger * 2; result := LValue; end; .... However, the following operator references a global table variable, and is therefore not literal: .... create operator NonLiteralOperator() : Integer begin result := Count(TableVars); end; .... The optimizer uses the literal characteristic to determine whether or not it can evaluate a given branch of an expression, and examine the result at compile-time for use in determining access paths, or for parameterization during distributed query processing. The following examples illustrate various literal and non-literal expressions: .... // literal // Integer selector invocation 5; // non-literal // invocation of non-literal operator DateTime() DateTime(); // literal // DateTime selector invocation with literal arguments Date(2004, 10, 20); .... [[DDGModelingProcessLogic-Characteristics-Remotable]] === Remotable The remotable characteristic allows the compiler to distinguish between objects and statements that reference global state (objects in the database), and ones that do not. Basically, an object or statement is remotable if it can be executed or evaluated without accessing any objects in the global catalog. Note that remotability is a characteristic not only of expressions and operator but of all catalog objects. The compiler uses the remotable characteristic to determine whether a particular operator invocation could take place within the presentation layer without accessing data on the server. This is used in the proposable interfaces to allow defaults, constraints, and other rules to be enforced by the presentation layer. When the presentation layer opens a data entry form for a table variable, for example, the first proposable call is the Default call, which determines the default values for each column in the new row. If the default definitions are remotable, they are downloaded to the Frontend client as part of the structure of the result set and evaluated there without the need for an additional network round-trip. [[DDGModelingProcessLogic-Characteristics-Functional]] === Functional The functional characteristic indicates whether an operator or expression has changed global state, usually by executing a data modification statement. Certain contexts such as constraint definitions require functional expressions. This guarantees that the act of validating a constraint will not change the state of the database. An operator is functional if it does not change global state. In other words, an operator that changes data in the database, such as a call to GetNextGenerator(), is not functional. An expression is functional if it does not contain any invocations of non-functional operators. [[DDGModelingProcessLogic-Characteristics-Deterministic]] === Deterministic The deterministic characteristic indicates whether successive evaluations of the expression will result in the same value. Certain contexts such as constraint definitions require deterministic expressions. This guarantees that once a constraint expression has been validated, it will be valid so long as the input remains the same. An operator is deterministic if it does not contain any invocations of non-deterministic operators. Likewise, an expression is deterministic if does not contain any invocations of non-deterministic operators. [[DDGModelingProcessLogic-Characteristics-Repeatable]] === Repeatable The repeatable characteristic indicates whether successive evaluations of the expression within the same transactional context will result in the same value. Repeatable is a stronger notion than deterministic in that a given expression may be non-deterministic but repeatable. For example, DateTime() is non-deterministic, but it is repeatable because successive invocations within the same transactional context will return the same value, namely the start time of the transaction. GetNextGenerator(), however, is not repeatable. Every invocation of the operator, regardless of transactional context will return a different value. Clearly, if an expression is deterministic, it is by definition repeatable. The repeatable characteristic is used by the compiler to ensure that operations such as restriction are well-defined, and by the optimizer to make distributed query processing decisions. An operator is repeatable if it does not contain any invocations of non-repeatable operators. Likewise, an expression is repeatable if it does not contain any invocations of non-repeatable operators. [[DDGModelingProcessLogic-Characteristics-Nilable]] === Nilable The nilable characteristic indicates whether a given expression or operator could evaluate to nil. Some expressions are nilable by definition, for example the *nil* keyword will always evaluate to nil, and is therefore nilable. Other expressions are nilable based on schema definitions. For example, referencing a column of a row within a table is nilable if the definition of that column is nilable. In general, an operator invocation is nilable if any of its arguments are nilable. For example, the following invocation of + is non-nilable: .... 1 + 1; .... This is because the expressions involved are not nilable, therefore the result could not be nil. The following addition expression, however, is nilable: .... begin var LX := nil; var LY := 2; LX + LY; end; .... This is because the expressions involved in the addition are variable references, which could contain a nil at run-time. The compiler therefore infers that the result of the addition could be nil. Some expressions are non-nilable by definition, for example the IsNil operator will always return **true**, or **false**, regardless of whether its arguments are nil. The nilable characteristic is used by the compiler and the query processor to perform various optimizations, and by the optimizer to determine whether given expression transformations are valid. [[DDGModelingProcessLogic-Characteristics-Order-Preserving]] === Order-Preserving The order-preserving characteristic indicates whether a given operator preserves the order semantics of its arguments. For example, conversion from a Byte to an Integer is an order-preserving operation. The order-preserving characteristic is used by the compiler to determine whether or not a given expression affects the use of a particular ordering during access path determination. [[DDGModelingProcessLogic-Characteristics-OverridingInferredCharacteristics]] === Overriding Inferred Characteristics In some cases, such as dynamic execution, it is not possible for the compiler to determine at compile-time the characteristics of a given expression or operator. In these cases, language modifiers can be used to override the inferred characteristics. Note that these should be used with extreme care, as incorrectly specifying the characteristics of an expression can lead to invalid optimization decisions by the compiler. Language Modifiers Characteristic ModifiersThe following table lists the language modifiers available for overriding characteristics within expressions: [cols="","",options=""header"",] |======================================================================= |Modifier |Description |IsLiteral |Overrides the inferred literal characteristic for the expression. |IsFunctional |Overrides the inferred functional characteristic for the expression. |IsDeterministic |Overrides the inferred deterministic characteristic for the expression. |IsRepeatable |Overrides the inferred repeatable characteristic for the expression. |IsNilable |Overrides the inferred nilable characteristic for the expression. |======================================================================= In addition to the ability to override the inferred characteristics for an expression, the inferred characteristics for an operator can be overridden using metadata tags. The following table lists tags available for overriding operator characteristics: [cols="","",options=""header"",] |======================================================================= |Tag |Description |DAE.IsRemotable |Overrides the inferred remotable characteristic for the operator. |DAE.IsLiteral |Overrides the inferred literal characteristic for the operator. |DAE.IsFunctional |Overrides the inferred functional characteristic for the operator. |DAE.IsDeterministic |Overrides the inferred deterministic characteristic for the operator. |DAE.IsRepeatable |Overrides the inferred repeatable characteristic for the operator. |DAE.IsNilable |Overrides the inferred nilable characteristic for the operator. |DAE.IsOrderPreserving |Overrides the inferred order-preserving characteristic for the operator. |======================================================================= The following example illustrates the use of language modifiers to set the characteristics of a dynamically evaluated expression: .... create operator CurrentLocationID() : LocationID begin result := ( Evaluate('CurrentLocation[].Location_ID') with { IsFunctional = ""true"", IsDeterministic = ""true"", IsRepeatable = ""true"" } ) as LocationID; end; .... Note that for dynamic evaluation, the query processor will verify that the characteristics of the dynamic expression match the characteristics specified using the modifiers. In fact, this example is somewhat contrived, because the default characteristics for dynamically evaluated expressions are assumed to be: non-literal, functional, deterministic, repeatable, and nilable. For dynamic execution, however, the compiler assumes non-literal, non-functional, non-deterministic, non-repeatable, and non-remotable, and the characteristic overrides will not be verified at run-time. The following example depicts the use of a characteristic override to allow the creation of a positive time-based constraint: .... alter table Contact { alter column NameSince { create constraint IsValid value <= (DateTime() with { IsDeterministic = ""true"" }) } }; .... Without the modifier, the compiler will disallow the creation of this constraint because it involves an invocation of the non-deterministic operator DateTime(). However, because the value is required to be less than or equal to the current date and time (an ever-increasing value), we can safely inform the compiler that once this expression evaluates to true for a given value, it will be true from that time forward. Note that the opposite formulation of this constraint (**value** >= DateTime()) is not valid, because at some point, the constraint will be violated by data that has already passed validation of the constraint footnote:[As an aside, we note that changing the value of the system clock to a date and time prior to the date and time of some existing row would also have the affect of invalidating previously validated data. However, this is something outside the control of the system and falls more in the category of outside tampering than logical constraint enforcement. For example, one could just as easily rearrange bits on the physical drive without the knowledge of the system in order to produce a violation of previously validated data.]. For more information on dynamic execution, see the <> section. [[D4LGProgrammingTopics-DynamicExecution]] == Dynamic Execution The Dataphor Server has system-provided operators which allow for the dynamic execution of D4 statements. The link:O-System.Execute.html[Execute] operator allows a given statement to be executed, the link:O-System.Evaluate.html[Evaluate] operator allows a given expression to be evaluated, while the link:O-System.Open.html[Open] operator allows a dynamic cursor to be declared and opened. The following example illustrates the use of these operators: .... create table Data { ID : Integer, key { ID } }; begin var LData : Integer := 10; Execute(""insert table { row { "" + LData.ToString() + "" ID } } into Data;""); end; select Evaluate('Data[10].ID') as Integer; begin var LSum : Integer := 0; var LCursor : cursor(table { ID : Integer }) := Open(""Data"") as cursor(table { ID : Integer }); try while LCursor.Next() do LSum := LSum + LCursor.Select().ID; finally LCursor.Close(); end; end; .... Note that when dynamically executing and evaluating D4, the inference mechanisms of the compiler do not occur until runtime. As a result, the Dataphor Server cannot determine the actual characteristics of a given statement or expression. For a discussion of how to override these characteristics at compiler-time, refer to the <> section. [[DDGModelingProcessLogic-Session-SpecificObjects]] == Session-specific Objects In addition to the global catalog, the Dataphor Server allows for session-specific objects to be created. These objects are visible only within the session in which they were created, and are automatically dropped when the session closes. The Dataphor Server allows for the creation of session-specific table variables, both base and derived, operators, and constraints, including references. Because the lifetime of these objects is limited to the current session, global catalog objects cannot reference session-specific catalog objects, but session-specific catalog objects can reference global objects. Other than the restrictions on dependencies mentioned above, session-specific objects behave exactly like their global counterparts. They can be used as seeds for user interface derivation in the Frontend, and they can participate in application transactions, just like global objects. To create a session-specific object, simply include the *session* keyword as part of the create statement. For example, the following statements create a session-specific table, and a session-specific reference from that table to the Location table: .... create session table CurrentLocation { Location_ID : LocationID, key { } }; create session reference CurrentLocation_Location CurrentLocation { Location_ID } references Location { ID } tags { Frontend.Lookup.Title = ""Current Location"" }; .... Note that the default storage device for session-specific tables is always the in-memory system device Temp. The Shipping application uses the CurrentLocation session table to track which location a user is currently logged into. When creating an invoice, this location will be used as the location for the invoice. In order to retrieve the current location, the following operator is used: .... //* Operator: CurrentLocationID() create operator CurrentLocationID() : LocationID begin result := Evaluate('CurrentLocation[].Location_ID') as LocationID; end; .... Because the CurrentLocationID() operator is a global catalog object, the compiler will not allow it to reference the CurrentLocation session table. As a result, we must use dynamic evaluation to retrieve the current location for the current session. The declared result type of the Evaluate call is **generic**, because the compiler has no way of determining at compile-time the result type of a dynamically evaluated expression. We must therefore _cast_ the resulting value as the type we know it will be using the *as* operator. This operator can then be used to construct the views and operators for the order entry user interfaces. For a continued discussion of these interfaces, refer to <> in the Presentation Layer part of this guide. [[DDGModelingProcessLogic-InvoiceProcessingExample]] == Invoice Processing Example As with any inventory management system, the Shipping Application must maintain current inventory levels at each location in response to sales and purchase orders, and shipping and receiving events. This is handled in the Shipping Application with a series of operators and event handlers. This section describes each of these operators, and how they are exposed in the application. The first operator, UpdateInventory, is responsible for updating the various inventory level indicators at a particular location. The following program listing provides the definition of this operator: .... create operator UpdateInventory ( const ALocationID : LocationID, const AItemTypeID : ItemTypeID, const ADeltaOnHand : Decimal, const ADeltaOnPurchase : Decimal, const ADeltaOnOrder : Decimal ) begin if exists ( LocationItem where Location_ID = ALocationID and ItemType_ID = AItemTypeID ) then begin update LocationItem set { OnHand := OnHand + ADeltaOnHand, OnPurchase := OnPurchase + ADeltaOnPurchase, OnOrder := OnOrder + ADeltaOnOrder } where Location_ID = ALocationID and ItemType_ID = AItemTypeID; end else begin insert table { row { ALocationID Location_ID, AItemTypeID ItemType_ID, ADeltaOnHand OnHand, ADeltaOnPurchase OnPurchase, ADeltaOnOrder OnOrder } } into LocationItem; end; end; .... This operator simply updates the OnHand, OnPurchase, and OnOrder levels for a given location (ALocationID) and a given item type (AItemTypeID). The creation of this operator dramatically simplifies the expression of the next operator, UpdateInvoice: .... //* Operator: UpdateInvoice create operator UpdateInvoice ( const AOldRow : typeof(Invoice[]), const ANewRow : typeof(Invoice[]) ) begin if AOldRow.Status_ID <> ANewRow.Status_ID then begin var LRow : typeof(InvoiceItem[]); var LIsPurchase := exists (PurchaseOrder where ID = ANewRow.ID); var LIsComplete := ANewRow.Status_ID = ""COM""; var LQuantity : Decimal; var LCursor := cursor ( InvoiceItem where Invoice_ID = ANewRow.ID ); try while LCursor.Next() do begin LRow := LCursor.Select(); LQuantity := LRow.Quantity; if LIsComplete then begin if LIsPurchase then // if this is a purchase order, // add LQuantity to OnHand, // and subtract it from OnPurchase UpdateInventory ( ANewRow.Location_ID, LRow.ItemType_ID, LQuantity, -LQuantity, 0 ) else // if this is a sales order, // subtract LQuantity from OnHand, // and subtract it from OnOrder UpdateInventory ( ANewRow.Location_ID, LRow.ItemType_ID, -LQuantity, 0, -LQuantity ); end else begin if LIsPurchase then // If this is a purchase order, // add LQuantity to OnPurchase UpdateInventory ( ANewRow.Location_ID, LRow.ItemType_ID, 0, LQuantity, 0 ) else // If this is a sales order, // add LQuantity to OnOrder UpdateInventory ( ANewRow.Location_ID, LRow.ItemType_ID, 0, 0, LQuantity ); end; end; finally LCursor.Close(); end; end; end; attach operator UpdateInvoice to Invoice on after update; .... This operator is attached as an event handler to the Invoice table. It responds to changes in the Status_ID of the invoice by updating inventory levels at each location as appropriate. The status of an invoice can be one of NEW, PRO, or COM (new, processed or complete). In addition, there is a transaction constraint in the Invoice table that prevents the status from moving backwards. The status of an invoice may only move from new to processed, to complete. These statuses correspond with placing an order, either from a customer via a sales order, or to a vendor via a purchase order, approving the order internally, and then either shipping the order to the customer, or receiving it from the vendor. When an invoice is processed, if it is a purchase order, the OnPurchase level for the item type is increased, otherwise the OnOrder level for the item type is increased. When an invoice is completed, if it is a purchase order, the OnPurchase level for the item type is decreased, and the OnHand level is increased. For a sales order, both the OnOrder and OnHand levels are decreased. Rather than allow the invoice status to be edited through a user interface, we simply provide an operator to perform the update, and then expose the operator in the presentation layer of the application. We will build the user interfaces that do this in Part III. The following listing shows the operators that perform the update: .... //* Operator: ProcessInvoice create operator ProcessInvoice(const AInvoiceID : InvoiceID) begin update Invoice set { Status_ID := ""PRO"" } where ID = AInvoiceID; end; //* Operator: CompleteInvoice create operator CompleteInvoice(const AInvoiceID : InvoiceID) begin update Invoice set { Status_ID := ""COM"" } where ID = AInvoiceID; end; .... ",16321,False,2456.3698234530175,median "// tag::HeaderFullDisplayName[] = workflow.ProcedureDependency - U // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--antorareferencedlist: :ExistsProperty--antorareferencinglist: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--pk_index_guid: :ExistsProperty--pk_indexpatterncolumndatatype: :ExistsProperty--pk_indexpatterncolumnname: :ExistsProperty--referencedobjectlist: :ExistsProperty--FK: :ExistsProperty--AntoraIndexList: :ExistsProperty--Columns: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] CBE20E01-119D-EB11-84F6-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] workflow.ProcedureDependency // end::RepoObject_FullDisplayName2[] == SysObject_type // tag::SysObject_type[] U // end::SysObject_type[] == SysObject_type_name // tag::SysObject_type_name[] user table // end::SysObject_type_name[] == SysObject_id // tag::SysObject_id[] 2082822482 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-11-28 12:10:36 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] [discrete] == _ [#column-id] === id [cols=""d,8a,m,m,m""] |=== |1 |*id* |int |NOT NULL |(1,1) |=== .Referencing Columns -- * xref:workflow.proceduredependency_gross.adoc#column-id[+workflow.ProcedureDependency_gross.id+] -- [#column-description] === Description [cols=""d,8a,m,m,m""] |=== | |Description |nvarchar(4000) |NULL | |=== .Referencing Columns -- * xref:workflow.proceduredependency_gross.adoc#column-description[+workflow.ProcedureDependency_gross.Description+] -- [#column-isunderlineactive] === is_active [cols=""d,8a,m,m,m""] |=== | |is_active .Default: DF_ProcedureDependency_is_active [source,sql] ---- ((1)) ---- |bit |NOT NULL | |=== .Referencing Columns -- * xref:workflow.proceduredependency_gross.adoc#column-isunderlineactive[+workflow.ProcedureDependency_gross.is_active+] -- [#column-isunderlinepersistencedependency] === is_PersistenceDependency [cols=""d,8a,m,m,m""] |=== | |is_PersistenceDependency .Default: DF_ProcedureDependency_is_PersistenceDependency [source,sql] ---- ((0)) ---- |bit |NOT NULL | |=== .Referencing Columns -- * xref:workflow.proceduredependency_gross.adoc#column-isunderlinepersistencedependency[+workflow.ProcedureDependency_gross.is_PersistenceDependency+] * xref:workflow.proceduredependency_input_persistencedependency.adoc#column-isunderlinepersistencedependency[+workflow.ProcedureDependency_input_PersistenceDependency.is_PersistenceDependency+] * xref:workflow.proceduredependency_persistencedependency_tgt.adoc#column-isunderlinepersistencedependency[+workflow.ProcedureDependency_PersistenceDependency_tgt.is_PersistenceDependency+] -- [#column-referencedunderlineprocedureunderlinerepoobjectunderlineguid] === referenced_Procedure_RepoObject_guid [cols=""d,8a,m,m,m""] |=== | |referenced_Procedure_RepoObject_guid |uniqueidentifier |NOT NULL | |=== .Referencing Columns -- * xref:workflow.proceduredependency_gross.adoc#column-referencedunderlineprocedureunderlinerepoobjectunderlineguid[+workflow.ProcedureDependency_gross.referenced_Procedure_RepoObject_guid+] * xref:workflow.proceduredependency_input_persistencedependency.adoc#column-referencedunderlineprocedureunderlinerepoobjectunderlineguid[+workflow.ProcedureDependency_input_PersistenceDependency.referenced_Procedure_RepoObject_guid+] * xref:workflow.proceduredependency_persistencedependency_tgt.adoc#column-referencedunderlineprocedureunderlinerepoobjectunderlineguid[+workflow.ProcedureDependency_PersistenceDependency_tgt.referenced_Procedure_RepoObject_guid+] * xref:workflow.workflow_proceduredependency.adoc#column-referencedunderlineprocedureunderlinerepoobjectunderlineguid[+workflow.Workflow_ProcedureDependency.referenced_Procedure_RepoObject_guid+] * xref:workflow.workflow_proceduredependency_all.adoc#column-referencedunderlineprocedureunderlinerepoobjectunderlineguid[+workflow.Workflow_ProcedureDependency_all.referenced_Procedure_RepoObject_guid+] -- [#column-referencedunderlinerepoobjectunderlineguid] === referenced_RepoObject_guid [cols=""d,8a,m,m,m""] |=== | |referenced_RepoObject_guid |uniqueidentifier |NULL | |=== [#column-referencingunderlineprocedureunderlinerepoobjectunderlineguid] === referencing_Procedure_RepoObject_guid [cols=""d,8a,m,m,m""] |=== | |referencing_Procedure_RepoObject_guid |uniqueidentifier |NOT NULL | |=== .Referencing Columns -- * xref:workflow.proceduredependency_gross.adoc#column-referencingunderlineprocedureunderlinerepoobjectunderlineguid[+workflow.ProcedureDependency_gross.referencing_Procedure_RepoObject_guid+] * xref:workflow.proceduredependency_input_persistencedependency.adoc#column-referencingunderlineprocedureunderlinerepoobjectunderlineguid[+workflow.ProcedureDependency_input_PersistenceDependency.referencing_Procedure_RepoObject_guid+] * xref:workflow.proceduredependency_persistencedependency_tgt.adoc#column-referencingunderlineprocedureunderlinerepoobjectunderlineguid[+workflow.ProcedureDependency_PersistenceDependency_tgt.referencing_Procedure_RepoObject_guid+] * xref:workflow.workflow_proceduredependency.adoc#column-referencingunderlineprocedureunderlinerepoobjectunderlineguid[+workflow.Workflow_ProcedureDependency.referencing_Procedure_RepoObject_guid+] * xref:workflow.workflow_proceduredependency_all.adoc#column-referencingunderlineprocedureunderlinerepoobjectunderlineguid[+workflow.Workflow_ProcedureDependency_all.referencing_Procedure_RepoObject_guid+] -- [#column-referencingunderlinerepoobjectunderlineguid] === referencing_RepoObject_guid [cols=""d,8a,m,m,m""] |=== | |referencing_RepoObject_guid |uniqueidentifier |NULL | |=== // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] |1 |*<>* |int |NOT NULL |(1,1) // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] | |<> |nvarchar(4000) |NULL | | |<> .Default: DF_ProcedureDependency_is_active [source,sql] ---- ((1)) ---- |bit |NOT NULL | | |<> .Default: DF_ProcedureDependency_is_PersistenceDependency [source,sql] ---- ((0)) ---- |bit |NOT NULL | | |<> |uniqueidentifier |NOT NULL | | |<> |uniqueidentifier |NULL | | |<> |uniqueidentifier |NOT NULL | | |<> |uniqueidentifier |NULL | // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] [#index-pkunderlineproceduredependency] === PK_ProcedureDependency * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; int -- * PK, Unique, Real: 1, 1, 1 [#index-ukunderlineproceduredependency] === UK_ProcedureDependency * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; uniqueidentifier * <>; uniqueidentifier -- * PK, Unique, Real: 0, 1, 1 [#index-idxunderlineproceduredependencyunderlineunderline1] === idx_ProcedureDependency++__++1 * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; uniqueidentifier -- * PK, Unique, Real: 0, 0, 0 * ++FK_ProcedureDependency_RepoObject_referenced++ + referenced: xref:repo.repoobject.adoc[], xref:repo.repoobject.adoc#index-pkunderlinerepoobject[+PK_RepoObject+] * is disabled [#index-idxunderlineproceduredependencyunderlineunderline2] === idx_ProcedureDependency++__++2 * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; uniqueidentifier -- * PK, Unique, Real: 0, 0, 0 * ++FK_ProcedureDependency_RepoObject_referencing++ + referenced: xref:repo.repoobject.adoc[], xref:repo.repoobject.adoc#index-pkunderlinerepoobject[+PK_RepoObject+] * is disabled // end::AntoraIndexList[] == AntoraMeasureDetails // tag::AntoraMeasureDetails[] // end::AntoraMeasureDetails[] == AntoraMeasureDescriptions == AntoraParameterList // tag::AntoraParameterList[] // end::AntoraParameterList[] == AntoraXrefCulturesList // tag::AntoraXrefCulturesList[] * xref:dhw:sqldb:workflow.proceduredependency.adoc[] - // end::AntoraXrefCulturesList[] == cultures_count // tag::cultures_count[] 1 // end::cultures_count[] == Other tags source: property.RepoObjectProperty_cross As rop_cross === additional_reference_csv // tag::additional_reference_csv[] // end::additional_reference_csv[] === AdocUspSteps // tag::adocuspsteps[] // end::adocuspsteps[] === AntoraReferencedList // tag::antorareferencedlist[] * xref:dhw:sqldb:workflow.proceduredependency_persistencedependency_tgt.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:workflow.proceduredependency_gross.adoc[] * xref:dhw:sqldb:workflow.proceduredependency_input_persistencedependency.adoc[] * xref:dhw:sqldb:workflow.workflow_proceduredependency.adoc[] * xref:dhw:sqldb:workflow.workflow_proceduredependency_all.adoc[] // end::antorareferencinglist[] === Description // tag::description[] // end::description[] === exampleUsage // tag::exampleusage[] // end::exampleusage[] === exampleUsage_2 // tag::exampleusage_2[] // end::exampleusage_2[] === exampleUsage_3 // tag::exampleusage_3[] // end::exampleusage_3[] === exampleUsage_4 // tag::exampleusage_4[] // end::exampleusage_4[] === exampleUsage_5 // tag::exampleusage_5[] // end::exampleusage_5[] === exampleWrong_Usage // tag::examplewrong_usage[] // end::examplewrong_usage[] === has_execution_plan_issue // tag::has_execution_plan_issue[] // end::has_execution_plan_issue[] === has_get_referenced_issue // tag::has_get_referenced_issue[] // end::has_get_referenced_issue[] === has_history // tag::has_history[] // end::has_history[] === has_history_columns // tag::has_history_columns[] // end::has_history_columns[] === InheritanceType // tag::inheritancetype[] // end::inheritancetype[] === is_persistence // tag::is_persistence[] // end::is_persistence[] === is_persistence_check_duplicate_per_pk // tag::is_persistence_check_duplicate_per_pk[] // end::is_persistence_check_duplicate_per_pk[] === is_persistence_check_for_empty_source // tag::is_persistence_check_for_empty_source[] // end::is_persistence_check_for_empty_source[] === is_persistence_delete_changed // tag::is_persistence_delete_changed[] // end::is_persistence_delete_changed[] === is_persistence_delete_missing // tag::is_persistence_delete_missing[] // end::is_persistence_delete_missing[] === is_persistence_insert // tag::is_persistence_insert[] // end::is_persistence_insert[] === is_persistence_truncate // tag::is_persistence_truncate[] // end::is_persistence_truncate[] === is_persistence_update_changed // tag::is_persistence_update_changed[] // end::is_persistence_update_changed[] === is_repo_managed // tag::is_repo_managed[] 0 // end::is_repo_managed[] === is_ssas // tag::is_ssas[] 0 // end::is_ssas[] === microsoft_database_tools_support // tag::microsoft_database_tools_support[] // end::microsoft_database_tools_support[] === MS_Description // tag::ms_description[] // end::ms_description[] === persistence_source_RepoObject_fullname // tag::persistence_source_repoobject_fullname[] // end::persistence_source_repoobject_fullname[] === persistence_source_RepoObject_fullname2 // tag::persistence_source_repoobject_fullname2[] // end::persistence_source_repoobject_fullname2[] === persistence_source_RepoObject_guid // tag::persistence_source_repoobject_guid[] // end::persistence_source_repoobject_guid[] === persistence_source_RepoObject_xref // tag::persistence_source_repoobject_xref[] // end::persistence_source_repoobject_xref[] === pk_index_guid // tag::pk_index_guid[] CEE20E01-119D-EB11-84F6-A81E8446D5B0 // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] int // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] id // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] * [workflow].[ProcedureDependency_PersistenceDependency_tgt] // end::referencedobjectlist[] === usp_persistence_RepoObject_guid // tag::usp_persistence_repoobject_guid[] // end::usp_persistence_repoobject_guid[] === UspExamples // tag::uspexamples[] // end::uspexamples[] === uspgenerator_usp_id // tag::uspgenerator_usp_id[] // end::uspgenerator_usp_id[] === UspParameters // tag::uspparameters[] // end::uspparameters[] == Boolean Attributes source: property.RepoObjectProperty WHERE property_int = 1 // tag::boolean_attributes[] // end::boolean_attributes[] == PlantUML diagrams === PlantUML Entity // tag::puml_entity[] [plantuml, entity-{docname}, svg, subs=macros] .... 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:workflow.proceduredependency.adoc[]"" as workflow.ProcedureDependency << U >> { - **id** : (int) Description : (nvarchar(4000)) - is_active : (bit) - is_PersistenceDependency : (bit) - referenced_Procedure_RepoObject_guid : (uniqueidentifier) referenced_RepoObject_guid : (uniqueidentifier) - referencing_Procedure_RepoObject_guid : (uniqueidentifier) referencing_RepoObject_guid : (uniqueidentifier) -- } .... // end::puml_entity[] === PlantUML Entity 1 1 FK // tag::puml_entity_1_1_fk[] [plantuml, entity_1_1_fk-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { **PK_RepoObject** .. RepoObject_guid; uniqueidentifier -- UK_RepoObject__RepoNames .. RepoObject_schema_name; nvarchar(128) RepoObject_name; nvarchar(128) -- UK_RepoObject__SysNames .. SysObject_schema_name; nvarchar(128) SysObject_name; nvarchar(128) -- - idx_RepoObject__1 .. pk_index_guid; uniqueidentifier } entity ""puml-link:dhw:sqldb:workflow.proceduredependency.adoc[]"" as workflow.ProcedureDependency << U >> { **PK_ProcedureDependency** .. id; int -- UK_ProcedureDependency .. referenced_Procedure_RepoObject_guid; uniqueidentifier referencing_Procedure_RepoObject_guid; uniqueidentifier -- - idx_ProcedureDependency__1 .. referenced_Procedure_RepoObject_guid; uniqueidentifier -- - idx_ProcedureDependency__2 .. referencing_Procedure_RepoObject_guid; uniqueidentifier } ""repo.RepoObject::PK_RepoObject"" <-- ""workflow.ProcedureDependency::idx_ProcedureDependency__2"" ""repo.RepoObject::PK_RepoObject"" <-- ""workflow.ProcedureDependency::idx_ProcedureDependency__1"" footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_fk[] === PlantUML 1 1 ObjectRef // tag::puml_entity_1_1_objectref[] [plantuml, entity_1_1_objectref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:workflow.proceduredependency.adoc[]"" as workflow.ProcedureDependency << U >> { - **id** : (int) -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency_gross.adoc[]"" as workflow.ProcedureDependency_gross << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency_input_persistencedependency.adoc[]"" as workflow.ProcedureDependency_input_PersistenceDependency << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency_persistencedependency_tgt.adoc[]"" as workflow.ProcedureDependency_PersistenceDependency_tgt << V >> { **referenced_Procedure_RepoObject_guid** : (uniqueidentifier) **referencing_Procedure_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency.adoc[]"" as workflow.Workflow_ProcedureDependency << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_all.adoc[]"" as workflow.Workflow_ProcedureDependency_all << V >> { -- } workflow.ProcedureDependency <.. workflow.ProcedureDependency_gross workflow.ProcedureDependency <.. workflow.ProcedureDependency_input_PersistenceDependency workflow.ProcedureDependency <.. workflow.Workflow_ProcedureDependency_all workflow.ProcedureDependency <.. workflow.Workflow_ProcedureDependency workflow.ProcedureDependency_PersistenceDependency_tgt <.. workflow.ProcedureDependency footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_objectref[] === PlantUML 30 0 ObjectRef // tag::puml_entity_30_0_objectref[] [plantuml, entity_30_0_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:config.ftv_dwh_database.adoc[]"" as config.ftv_dwh_database << IF >> { -- } entity ""puml-link:dhw:sqldb:config.ftv_get_parameter_value.adoc[]"" as config.ftv_get_parameter_value << IF >> { -- } entity ""puml-link:dhw:sqldb:config.parameter.adoc[]"" as config.Parameter << U >> { - **Parameter_name** : (varchar(100)) - **sub_Parameter** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:configt.parameter_default.adoc[]"" as configT.Parameter_default << V >> { - **Parameter_name** : (varchar(52)) - **sub_Parameter** : (nvarchar(26)) -- } entity ""puml-link:dhw:sqldb:configt.spt_values.adoc[]"" as configT.spt_values << U >> { -- } entity ""puml-link:dhw:sqldb:configt.type.adoc[]"" as configT.type << V >> { **type** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:docs.fs_cleanstringforfilename.adoc[]"" as docs.fs_cleanStringForFilename << FN >> { -- } entity ""puml-link:dhw:sqldb:property.external_repoobjectproperty.adoc[]"" as property.external_RepoObjectProperty << U >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.fs_get_repoobjectproperty_nvarchar.adoc[]"" as property.fs_get_RepoObjectProperty_nvarchar << FN >> { -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject.adoc[]"" as property.PropertyName_RepoObject << V >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject_t.adoc[]"" as property.PropertyName_RepoObject_T << U >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty.adoc[]"" as property.RepoObjectProperty << U >> { - **RepoObjectProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_src.adoc[]"" as property.RepoObjectProperty_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_tgt.adoc[]"" as property.RepoObjectProperty_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_selectedpropertyname_split.adoc[]"" as property.RepoObjectProperty_SelectedPropertyName_split << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference.adoc[]"" as reference.additional_Reference << U >> { - **Id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_database.adoc[]"" as reference.additional_Reference_database << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_database_t.adoc[]"" as reference.additional_Reference_database_T << U >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_src.adoc[]"" as reference.additional_Reference_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_tgt.adoc[]"" as reference.additional_Reference_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_src.adoc[]"" as reference.additional_Reference_from_ssas_src << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_tgt.adoc[]"" as reference.additional_Reference_from_ssas_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_guid.adoc[]"" as reference.additional_Reference_guid << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_is_external.adoc[]"" as reference.additional_Reference_is_external << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object.adoc[]"" as reference.additional_Reference_Object << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object_t.adoc[]"" as reference.additional_Reference_Object_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_objectcolumn.adoc[]"" as reference.additional_Reference_ObjectColumn << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) **ColumnName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_objectcolumn_t.adoc[]"" as reference.additional_Reference_ObjectColumn_T << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_src.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_tgt.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.persistence.adoc[]"" as reference.Persistence << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_queryplan.adoc[]"" as reference.RepoObject_QueryPlan << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference.adoc[]"" as reference.RepoObject_reference << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_additional.adoc[]"" as reference.RepoObject_reference_additional << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_persistence.adoc[]"" as reference.RepoObject_reference_persistence << V >> { **referenced_RepoObject_guid** : (uniqueidentifier) - **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_persistence_target_as_source.adoc[]"" as reference.RepoObject_reference_persistence_target_as_source << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_sqlexpressiondependencies.adoc[]"" as reference.RepoObject_reference_SqlExpressionDependencies << V >> { **referenced_RepoObject_guid** : (uniqueidentifier) **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_t.adoc[]"" as reference.RepoObject_reference_T << U >> { **referenced_RepoObject_guid** : (uniqueidentifier) **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_union.adoc[]"" as reference.RepoObject_reference_union << V >> { **referenced_RepoObject_guid** : (uniqueidentifier) **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobject_reference_virtual.adoc[]"" as reference.RepoObject_reference_virtual << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_referencedreferencing.adoc[]"" as reference.RepoObject_ReferencedReferencing << V >> { -- } entity ""puml-link:dhw:sqldb:reference.repoobject_referencetree.adoc[]"" as reference.RepoObject_ReferenceTree << U >> { - **RepoObject_guid** : (uniqueidentifier) **Referenced_Depth** : (int) **Referencing_Depth** : (int) - **Referenced_guid** : (uniqueidentifier) - **Referencing_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.repoobjectsource_virtual.adoc[]"" as reference.RepoObjectSource_virtual << U >> { - **RepoObject_guid** : (uniqueidentifier) - **Source_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.index_settings.adoc[]"" as repo.Index_Settings << U >> { - **index_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_src.adoc[]"" as repo.RepoObject_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_tgt.adoc[]"" as repo.RepoObject_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_gross.adoc[]"" as repo.RepoObject_gross << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_gross_persistence.adoc[]"" as repo.RepoObject_gross_persistence << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_persistence.adoc[]"" as repo.RepoObject_persistence << U >> { - **target_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_src.adoc[]"" as repo.RepoObject_SSAS_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_tgt.adoc[]"" as repo.RepoObject_SSAS_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn.adoc[]"" as repo.RepoObjectColumn << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_external_src.adoc[]"" as repo.RepoObjectColumn_external_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_external_tgt.adoc[]"" as repo.RepoObjectColumn_external_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_ssas_src.adoc[]"" as repo.RepoObjectColumn_SSAS_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_ssas_tgt.adoc[]"" as repo.RepoObjectColumn_SSAS_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema.adoc[]"" as repo.RepoSchema << U >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_src.adoc[]"" as repo.RepoSchema_ssas_src << V >> { - **RepoSchema_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_tgt.adoc[]"" as repo.RepoSchema_ssas_tgt << V >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.syscolumn_repoobjectcolumn_via_name.adoc[]"" as repo.SysColumn_RepoObjectColumn_via_name << V >> { -- } entity ""puml-link:dhw:sqldb:repo.sysobject_repoobject_via_name.adoc[]"" as repo.SysObject_RepoObject_via_name << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.extendedproperties.adoc[]"" as repo_sys.ExtendedProperties << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.sql_expression_dependencies.adoc[]"" as repo_sys.sql_expression_dependencies << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.syscolumn.adoc[]"" as repo_sys.SysColumn << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.sysobject.adoc[]"" as repo_sys.SysObject << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.additional_reference_step1.adoc[]"" as ssas.additional_Reference_step1 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json.adoc[]"" as ssas.model_json << U >> { - **databasename** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_10.adoc[]"" as ssas.model_json_10 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_20.adoc[]"" as ssas.model_json_20 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_201_descriptions_multiline.adoc[]"" as ssas.model_json_201_descriptions_multiline << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_2011_descriptions_stragg.adoc[]"" as ssas.model_json_2011_descriptions_StrAgg << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables.adoc[]"" as ssas.model_json_31_tables << V >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables_t.adoc[]"" as ssas.model_json_31_tables_T << U >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[]"" as ssas.model_json_311_tables_columns << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[]"" as ssas.model_json_311_tables_columns_T << U >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313_tables_partitions.adoc[]"" as ssas.model_json_313_tables_partitions << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131_tables_partitions_source.adoc[]"" as ssas.model_json_3131_tables_partitions_source << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) **tables_partitions_source_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311_tables_partitions_source_posfrom.adoc[]"" as ssas.model_json_31311_tables_partitions_source_PosFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313111_tables_partitions_source_stringfrom.adoc[]"" as ssas.model_json_313111_tables_partitions_source_StringFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131111_tables_partitions_source_posdot.adoc[]"" as ssas.model_json_3131111_tables_partitions_source_PosDot << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311111_tables_partitions_source_part123.adoc[]"" as ssas.model_json_31311111_tables_partitions_source_Part123 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_316_tables_descriptions_multiline.adoc[]"" as ssas.model_json_316_tables_descriptions_multiline << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3161_tables_descriptions_stragg.adoc[]"" as ssas.model_json_3161_tables_descriptions_StrAgg << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources.adoc[]"" as ssas.model_json_33_dataSources << V >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources_t.adoc[]"" as ssas.model_json_33_dataSources_T << U >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:sys_dwh.columns.adoc[]"" as sys_dwh.columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.computed_columns.adoc[]"" as sys_dwh.computed_columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.default_constraints.adoc[]"" as sys_dwh.default_constraints << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.extended_properties.adoc[]"" as sys_dwh.extended_properties << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.identity_columns.adoc[]"" as sys_dwh.identity_columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.indexes.adoc[]"" as sys_dwh.indexes << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.objects.adoc[]"" as sys_dwh.objects << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.parameters.adoc[]"" as sys_dwh.parameters << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.schemas.adoc[]"" as sys_dwh.schemas << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.sql_expression_dependencies.adoc[]"" as sys_dwh.sql_expression_dependencies << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.sql_modules.adoc[]"" as sys_dwh.sql_modules << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.tables.adoc[]"" as sys_dwh.tables << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.types.adoc[]"" as sys_dwh.types << SN >> { -- } entity ""puml-link:dhw:sqldb:uspgenerator.generatorusp.adoc[]"" as uspgenerator.GeneratorUsp << U >> { - **id** : (int) -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency.adoc[]"" as workflow.ProcedureDependency << U >> { - **id** : (int) -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency_persistencedependency_src.adoc[]"" as workflow.ProcedureDependency_PersistenceDependency_src << V >> { **referenced_Procedure_RepoObject_guid** : (uniqueidentifier) **referencing_Procedure_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency_persistencedependency_tgt.adoc[]"" as workflow.ProcedureDependency_PersistenceDependency_tgt << V >> { **referenced_Procedure_RepoObject_guid** : (uniqueidentifier) **referencing_Procedure_RepoObject_guid** : (uniqueidentifier) -- } config.ftv_dwh_database <.. repo_sys.sql_expression_dependencies config.ftv_dwh_database <.. repo_sys.ExtendedProperties config.ftv_dwh_database <.. repo_sys.SysColumn config.ftv_get_parameter_value <.. repo.RepoObject_external_src config.ftv_get_parameter_value <.. ssas.additional_Reference_step1 config.ftv_get_parameter_value <.. reference.additional_Reference_is_external config.ftv_get_parameter_value <.. repo.RepoObject_gross config.Parameter <.. property.PropertyName_RepoObject config.Parameter <.. config.ftv_dwh_database config.Parameter <.. config.ftv_get_parameter_value configT.Parameter_default <.. config.Parameter configT.spt_values <.. configT.type configT.type <.. reference.RepoObject_ReferencedReferencing configT.type <.. repo.RepoObject_gross_persistence configT.type <.. repo.RepoObject_gross docs.fs_cleanStringForFilename <.. repo.RepoObject_gross_persistence docs.fs_cleanStringForFilename <.. reference.RepoObject_ReferencedReferencing docs.fs_cleanStringForFilename <.. repo.RepoObject_gross property.external_RepoObjectProperty <.. property.RepoObjectProperty_external_src property.fs_get_RepoObjectProperty_nvarchar <.. repo.RepoObject_gross property.PropertyName_RepoObject <.. property.PropertyName_RepoObject_T property.PropertyName_RepoObject_T <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty <.. property.PropertyName_RepoObject property.RepoObjectProperty <.. property.RepoObjectProperty_SelectedPropertyName_split property.RepoObjectProperty <.. property.fs_get_RepoObjectProperty_nvarchar property.RepoObjectProperty_external_src <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty_external_tgt <.. property.RepoObjectProperty property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_from_properties_src property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_wo_columns_from_properties_src reference.additional_Reference <.. reference.additional_Reference_guid reference.additional_Reference <.. reference.additional_Reference_is_external reference.additional_Reference_database <.. reference.additional_Reference_database_T reference.additional_Reference_database_T <.. repo.RepoObject_gross reference.additional_Reference_from_properties_src <.. reference.additional_Reference_from_properties_tgt reference.additional_Reference_from_properties_tgt <.. reference.additional_Reference reference.additional_Reference_from_ssas_src <.. reference.additional_Reference_from_ssas_tgt reference.additional_Reference_from_ssas_tgt <.. reference.additional_Reference reference.additional_Reference_guid <.. reference.RepoObject_reference_additional reference.additional_Reference_is_external <.. reference.additional_Reference_ObjectColumn reference.additional_Reference_is_external <.. reference.additional_Reference_database reference.additional_Reference_is_external <.. reference.additional_Reference_Object reference.additional_Reference_Object <.. reference.additional_Reference_Object_T reference.additional_Reference_Object_T <.. repo.RepoObject_external_src reference.additional_Reference_Object_T <.. repo.RepoObjectColumn_external_src reference.additional_Reference_ObjectColumn <.. reference.additional_Reference_ObjectColumn_T reference.additional_Reference_ObjectColumn_T <.. repo.RepoObjectColumn_external_src reference.additional_Reference_wo_columns_from_properties_src <.. reference.additional_Reference_wo_columns_from_properties_tgt reference.additional_Reference_wo_columns_from_properties_tgt <.. reference.additional_Reference reference.Persistence <.. workflow.ProcedureDependency_PersistenceDependency_src reference.RepoObject_QueryPlan <.. repo.RepoObject_gross reference.RepoObject_reference <.. reference.RepoObject_reference_T reference.RepoObject_reference_additional <.. reference.RepoObject_reference_union reference.RepoObject_reference_persistence <.. reference.RepoObject_reference_union reference.RepoObject_reference_persistence_target_as_source <.. reference.RepoObject_reference_union reference.RepoObject_reference_persistence_target_as_source <.. reference.RepoObject_reference reference.RepoObject_reference_SqlExpressionDependencies <.. reference.RepoObject_reference_union reference.RepoObject_reference_SqlExpressionDependencies <.. reference.RepoObject_reference_persistence_target_as_source reference.RepoObject_reference_T <.. reference.RepoObject_ReferencedReferencing reference.RepoObject_reference_union <.. reference.RepoObject_reference reference.RepoObject_reference_virtual <.. reference.RepoObject_reference_union reference.RepoObject_ReferencedReferencing <.. repo.RepoObject_gross reference.RepoObject_ReferenceTree <.. reference.Persistence reference.RepoObjectSource_virtual <.. reference.RepoObject_reference_virtual repo.Index_Settings <.. repo.RepoObject_gross repo.RepoObject <.. reference.RepoObject_reference_persistence repo.RepoObject <.. repo.SysColumn_RepoObjectColumn_via_name repo.RepoObject <.. repo.SysObject_RepoObject_via_name repo.RepoObject <.. property.RepoObjectProperty_external_tgt repo.RepoObject <.. repo.RepoObjectColumn_external_src repo.RepoObject <.. repo.RepoObject_gross_persistence repo.RepoObject <.. reference.RepoObject_reference_SqlExpressionDependencies repo.RepoObject <.. repo.RepoObject_gross repo.RepoObject <.. repo.RepoObject_external_src repo.RepoObject <.. reference.RepoObject_reference_virtual repo.RepoObject <.. reference.additional_Reference_guid repo.RepoObject_external_src <.. repo.RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.RepoObject repo.RepoObject_external_tgt <.. repo.RepoObjectColumn_external_tgt repo.RepoObject_gross <.. reference.Persistence repo.RepoObject_gross_persistence <.. reference.RepoObject_reference_persistence_target_as_source repo.RepoObject_persistence <.. reference.RepoObject_reference_persistence repo.RepoObject_persistence <.. repo.RepoObject_gross repo.RepoObject_persistence <.. repo.RepoObject_gross_persistence repo.RepoObject_SSAS_src <.. repo.RepoObject_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObjectColumn_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObject repo.RepoObjectColumn <.. reference.additional_Reference_guid repo.RepoObjectColumn <.. repo.SysColumn_RepoObjectColumn_via_name repo.RepoObjectColumn_external_src <.. repo.RepoObjectColumn_external_tgt repo.RepoObjectColumn_external_tgt <.. repo.RepoObjectColumn repo.RepoObjectColumn_SSAS_src <.. repo.RepoObjectColumn_SSAS_tgt repo.RepoObjectColumn_SSAS_tgt <.. repo.RepoObjectColumn repo.RepoSchema <.. repo.RepoObject_SSAS_src repo.RepoSchema_ssas_src <.. repo.RepoSchema_ssas_tgt repo.RepoSchema_ssas_tgt <.. repo.RepoSchema repo.SysColumn_RepoObjectColumn_via_name <.. repo_sys.sql_expression_dependencies repo.SysObject_RepoObject_via_name <.. repo_sys.sql_expression_dependencies repo_sys.ExtendedProperties <.. repo_sys.SysObject repo_sys.ExtendedProperties <.. repo_sys.SysColumn repo_sys.sql_expression_dependencies <.. reference.RepoObject_reference_SqlExpressionDependencies repo_sys.SysColumn <.. repo.SysColumn_RepoObjectColumn_via_name repo_sys.SysObject <.. repo.SysObject_RepoObject_via_name repo_sys.SysObject <.. repo_sys.SysColumn ssas.additional_Reference_step1 <.. reference.additional_Reference_from_ssas_src ssas.model_json <.. ssas.model_json_10 ssas.model_json_10 <.. ssas.model_json_20 ssas.model_json_20 <.. repo.RepoSchema_ssas_src ssas.model_json_20 <.. ssas.model_json_201_descriptions_multiline ssas.model_json_20 <.. ssas.model_json_33_dataSources ssas.model_json_20 <.. ssas.model_json_31_tables ssas.model_json_201_descriptions_multiline <.. ssas.model_json_2011_descriptions_StrAgg ssas.model_json_2011_descriptions_StrAgg <.. repo.RepoSchema_ssas_src ssas.model_json_31_tables <.. ssas.model_json_31_tables_T ssas.model_json_31_tables_T <.. ssas.model_json_311_tables_columns ssas.model_json_31_tables_T <.. repo.RepoObject_SSAS_src ssas.model_json_31_tables_T <.. ssas.model_json_316_tables_descriptions_multiline ssas.model_json_31_tables_T <.. repo.RepoObject_gross ssas.model_json_31_tables_T <.. ssas.model_json_313_tables_partitions ssas.model_json_311_tables_columns <.. ssas.model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. repo.RepoObjectColumn_SSAS_src ssas.model_json_311_tables_columns_T <.. ssas.additional_Reference_step1 ssas.model_json_313_tables_partitions <.. ssas.model_json_3131_tables_partitions_source ssas.model_json_3131_tables_partitions_source <.. ssas.model_json_31311_tables_partitions_source_PosFrom ssas.model_json_31311_tables_partitions_source_PosFrom <.. ssas.model_json_313111_tables_partitions_source_StringFrom ssas.model_json_313111_tables_partitions_source_StringFrom <.. ssas.model_json_3131111_tables_partitions_source_PosDot ssas.model_json_3131111_tables_partitions_source_PosDot <.. ssas.model_json_31311111_tables_partitions_source_Part123 ssas.model_json_31311111_tables_partitions_source_Part123 <.. ssas.additional_Reference_step1 ssas.model_json_316_tables_descriptions_multiline <.. ssas.model_json_3161_tables_descriptions_StrAgg ssas.model_json_3161_tables_descriptions_StrAgg <.. repo.RepoObject_gross ssas.model_json_33_dataSources <.. ssas.model_json_33_dataSources_T ssas.model_json_33_dataSources_T <.. ssas.additional_Reference_step1 sys_dwh.columns <.. repo_sys.ExtendedProperties sys_dwh.columns <.. repo_sys.SysColumn sys_dwh.computed_columns <.. repo_sys.SysColumn sys_dwh.default_constraints <.. repo_sys.SysColumn sys_dwh.extended_properties <.. repo_sys.ExtendedProperties sys_dwh.identity_columns <.. repo_sys.SysColumn sys_dwh.indexes <.. repo_sys.ExtendedProperties sys_dwh.objects <.. repo_sys.ExtendedProperties sys_dwh.objects <.. repo_sys.SysObject sys_dwh.parameters <.. repo_sys.ExtendedProperties sys_dwh.schemas <.. repo_sys.SysObject sys_dwh.schemas <.. repo_sys.ExtendedProperties sys_dwh.sql_expression_dependencies <.. repo_sys.sql_expression_dependencies sys_dwh.sql_modules <.. repo_sys.SysObject sys_dwh.tables <.. repo_sys.SysObject sys_dwh.types <.. repo_sys.SysColumn uspgenerator.GeneratorUsp <.. repo.RepoObject_gross workflow.ProcedureDependency_PersistenceDependency_src <.. workflow.ProcedureDependency_PersistenceDependency_tgt workflow.ProcedureDependency_PersistenceDependency_tgt <.. workflow.ProcedureDependency footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_30_0_objectref[] === PlantUML 0 30 ObjectRef // tag::puml_entity_0_30_objectref[] [plantuml, entity_0_30_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:workflow.biml_package.adoc[]"" as workflow.Biml_Package << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.biml_precedenceconstraints.adoc[]"" as workflow.Biml_PrecedenceConstraints << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.biml_project.adoc[]"" as workflow.Biml_Project << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.biml_task.adoc[]"" as workflow.Biml_Task << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency.adoc[]"" as workflow.ProcedureDependency << U >> { - **id** : (int) -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency_gross.adoc[]"" as workflow.ProcedureDependency_gross << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency_input_persistencedependency.adoc[]"" as workflow.ProcedureDependency_input_PersistenceDependency << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.usp_persist_workflow_proceduredependency_t.adoc[]"" as workflow.usp_PERSIST_Workflow_ProcedureDependency_T << P >> { -- } entity ""puml-link:dhw:sqldb:workflow.usp_workflow.adoc[]"" as workflow.usp_workflow << P >> { -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency.adoc[]"" as workflow.Workflow_ProcedureDependency << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_all.adoc[]"" as workflow.Workflow_ProcedureDependency_all << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_t.adoc[]"" as workflow.Workflow_ProcedureDependency_T << U >> { - **Workflow_id** : (int) - **referenced_Procedure_RepoObject_guid** : (uniqueidentifier) - **referencing_Procedure_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_t_active.adoc[]"" as workflow.Workflow_ProcedureDependency_T_active << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_t_bidirectional.adoc[]"" as workflow.Workflow_ProcedureDependency_T_bidirectional << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_t_bidirectional_t.adoc[]"" as workflow.Workflow_ProcedureDependency_T_bidirectional_T << U >> { - **Workflow_id** : (int) - **referenced_Procedure_RepoObject_guid** : (uniqueidentifier) - **referencing_Procedure_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_t_notinsortorder.adoc[]"" as workflow.Workflow_ProcedureDependency_T_NotInSortorder << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_t_notinsortorder_check.adoc[]"" as workflow.Workflow_ProcedureDependency_T_NotInSortorder_check << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_t_redundant.adoc[]"" as workflow.Workflow_ProcedureDependency_T_redundant << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_t_taskname.adoc[]"" as workflow.Workflow_ProcedureDependency_T_TaskName << V >> { -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_wo_redundant.adoc[]"" as workflow.Workflow_ProcedureDependency_wo_redundant << V >> { -- } workflow.Biml_Package <.. workflow.Biml_Project workflow.Biml_PrecedenceConstraints <.. workflow.Biml_Task workflow.Biml_Task <.. workflow.Biml_Package workflow.ProcedureDependency <.. workflow.ProcedureDependency_gross workflow.ProcedureDependency <.. workflow.ProcedureDependency_input_PersistenceDependency workflow.ProcedureDependency <.. workflow.Workflow_ProcedureDependency_all workflow.ProcedureDependency <.. workflow.Workflow_ProcedureDependency workflow.usp_PERSIST_Workflow_ProcedureDependency_T <.. workflow.usp_workflow workflow.Workflow_ProcedureDependency <.. workflow.Workflow_ProcedureDependency_T workflow.Workflow_ProcedureDependency <.. workflow.usp_PERSIST_Workflow_ProcedureDependency_T workflow.Workflow_ProcedureDependency_all <.. workflow.Workflow_ProcedureDependency_wo_redundant workflow.Workflow_ProcedureDependency_T <.. workflow.usp_workflow workflow.Workflow_ProcedureDependency_T <.. workflow.Workflow_ProcedureDependency_T_bidirectional workflow.Workflow_ProcedureDependency_T <.. workflow.usp_PERSIST_Workflow_ProcedureDependency_T workflow.Workflow_ProcedureDependency_T <.. workflow.Workflow_ProcedureDependency_T_active workflow.Workflow_ProcedureDependency_T_active <.. workflow.Workflow_ProcedureDependency_T_NotInSortorder workflow.Workflow_ProcedureDependency_T_active <.. workflow.Workflow_ProcedureDependency_T_redundant workflow.Workflow_ProcedureDependency_T_active <.. workflow.Workflow_ProcedureDependency_T_TaskName workflow.Workflow_ProcedureDependency_T_bidirectional <.. workflow.usp_workflow workflow.Workflow_ProcedureDependency_T_bidirectional <.. workflow.Workflow_ProcedureDependency_T_bidirectional_T workflow.Workflow_ProcedureDependency_T_NotInSortorder <.. workflow.usp_workflow workflow.Workflow_ProcedureDependency_T_NotInSortorder <.. workflow.Workflow_ProcedureDependency_T_NotInSortorder_check workflow.Workflow_ProcedureDependency_T_NotInSortorder_check <.. workflow.usp_workflow workflow.Workflow_ProcedureDependency_T_redundant <.. workflow.usp_workflow workflow.Workflow_ProcedureDependency_T_redundant <.. workflow.Workflow_ProcedureDependency_wo_redundant workflow.Workflow_ProcedureDependency_T_TaskName <.. workflow.Biml_PrecedenceConstraints footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_0_30_objectref[] === PlantUML 1 1 ColumnRef // tag::puml_entity_1_1_colref[] [plantuml, entity_1_1_colref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:workflow.proceduredependency.adoc[]"" as workflow.ProcedureDependency << U >> { - **id** : (int) Description : (nvarchar(4000)) - is_active : (bit) - is_PersistenceDependency : (bit) - referenced_Procedure_RepoObject_guid : (uniqueidentifier) referenced_RepoObject_guid : (uniqueidentifier) - referencing_Procedure_RepoObject_guid : (uniqueidentifier) referencing_RepoObject_guid : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency_gross.adoc[]"" as workflow.ProcedureDependency_gross << V >> { Description : (nvarchar(4000)) - id : (int) - is_active : (bit) - is_PersistenceDependency : (bit) - referenced_Procedure_RepoObject_guid : (uniqueidentifier) - referenced_RepoObject_fullname : (nvarchar(261)) - referenced_RepoObject_fullname2 : (nvarchar(257)) - referenced_RepoObject_schema_name : (nvarchar(128)) - referencing_Procedure_RepoObject_guid : (uniqueidentifier) - referencing_RepoObject_fullname : (nvarchar(261)) - referencing_RepoObject_fullname2 : (nvarchar(257)) - referencing_RepoObject_schema_name : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency_input_persistencedependency.adoc[]"" as workflow.ProcedureDependency_input_PersistenceDependency << V >> { - is_PersistenceDependency : (int) referenced_Procedure_RepoObject_guid : (uniqueidentifier) referenced_RepoObject_guid : (uniqueidentifier) referencing_Procedure_RepoObject_guid : (uniqueidentifier) referencing_RepoObject_guid : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:workflow.proceduredependency_persistencedependency_tgt.adoc[]"" as workflow.ProcedureDependency_PersistenceDependency_tgt << V >> { **referenced_Procedure_RepoObject_guid** : (uniqueidentifier) **referencing_Procedure_RepoObject_guid** : (uniqueidentifier) - is_PersistenceDependency : (int) -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency.adoc[]"" as workflow.Workflow_ProcedureDependency << V >> { - referenced_Procedure_RepoObject_guid : (uniqueidentifier) - referencing_Procedure_RepoObject_guid : (uniqueidentifier) - Workflow_id : (int) -- } entity ""puml-link:dhw:sqldb:workflow.workflow_proceduredependency_all.adoc[]"" as workflow.Workflow_ProcedureDependency_all << V >> { - referenced_Procedure_RepoObject_guid : (uniqueidentifier) - referencing_Procedure_RepoObject_guid : (uniqueidentifier) - Workflow_id : (int) -- } workflow.ProcedureDependency <.. workflow.ProcedureDependency_gross workflow.ProcedureDependency <.. workflow.ProcedureDependency_input_PersistenceDependency workflow.ProcedureDependency <.. workflow.Workflow_ProcedureDependency_all workflow.ProcedureDependency <.. workflow.Workflow_ProcedureDependency workflow.ProcedureDependency_PersistenceDependency_tgt <.. workflow.ProcedureDependency ""workflow.ProcedureDependency::Description"" <-- ""workflow.ProcedureDependency_gross::Description"" ""workflow.ProcedureDependency::id"" <-- ""workflow.ProcedureDependency_gross::id"" ""workflow.ProcedureDependency::is_active"" <-- ""workflow.ProcedureDependency_gross::is_active"" ""workflow.ProcedureDependency::is_PersistenceDependency"" <-- ""workflow.ProcedureDependency_gross::is_PersistenceDependency"" ""workflow.ProcedureDependency::is_PersistenceDependency"" <-- ""workflow.ProcedureDependency_input_PersistenceDependency::is_PersistenceDependency"" ""workflow.ProcedureDependency::is_PersistenceDependency"" <-- ""workflow.ProcedureDependency_PersistenceDependency_tgt::is_PersistenceDependency"" ""workflow.ProcedureDependency::referenced_Procedure_RepoObject_guid"" <-- ""workflow.ProcedureDependency_PersistenceDependency_tgt::referenced_Procedure_RepoObject_guid"" ""workflow.ProcedureDependency::referenced_Procedure_RepoObject_guid"" <-- ""workflow.ProcedureDependency_input_PersistenceDependency::referenced_Procedure_RepoObject_guid"" ""workflow.ProcedureDependency::referenced_Procedure_RepoObject_guid"" <-- ""workflow.Workflow_ProcedureDependency_all::referenced_Procedure_RepoObject_guid"" ""workflow.ProcedureDependency::referenced_Procedure_RepoObject_guid"" <-- ""workflow.Workflow_ProcedureDependency::referenced_Procedure_RepoObject_guid"" ""workflow.ProcedureDependency::referenced_Procedure_RepoObject_guid"" <-- ""workflow.ProcedureDependency_gross::referenced_Procedure_RepoObject_guid"" ""workflow.ProcedureDependency::referencing_Procedure_RepoObject_guid"" <-- ""workflow.ProcedureDependency_gross::referencing_Procedure_RepoObject_guid"" ""workflow.ProcedureDependency::referencing_Procedure_RepoObject_guid"" <-- ""workflow.Workflow_ProcedureDependency::referencing_Procedure_RepoObject_guid"" ""workflow.ProcedureDependency::referencing_Procedure_RepoObject_guid"" <-- ""workflow.Workflow_ProcedureDependency_all::referencing_Procedure_RepoObject_guid"" ""workflow.ProcedureDependency::referencing_Procedure_RepoObject_guid"" <-- ""workflow.ProcedureDependency_input_PersistenceDependency::referencing_Procedure_RepoObject_guid"" ""workflow.ProcedureDependency::referencing_Procedure_RepoObject_guid"" <-- ""workflow.ProcedureDependency_PersistenceDependency_tgt::referencing_Procedure_RepoObject_guid"" footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_colref[] == sql_modules_definition // tag::sql_modules_definition[] [%collapsible] ======= [source,sql,numbered,indent=0] ---- ---- ======= // end::sql_modules_definition[] ",16262,True,3465.1134359391726,median "tag::aggregations[] If set, the {dfeed} performs aggregation searches. Support for aggregations is limited and should be used only with low cardinality data. For more information, see {ml-docs}/ml-configuring-aggregation.html[Aggregating data for faster performance]. end::aggregations[] tag::allow-lazy-open[] Advanced configuration option. Specifies whether this job can open when there is insufficient {ml} node capacity for it to be immediately assigned to a node. The default value is `false`; if a {ml} node with capacity to run the job cannot immediately be found, the <> returns an error. However, this is also subject to the cluster-wide `xpack.ml.max_lazy_ml_nodes` setting; see <>. If this option is set to `true`, the <> does not return an error and the job waits in the `opening` state until sufficient {ml} node capacity is available. end::allow-lazy-open[] tag::allow-lazy-start[] Whether this job should be allowed to start when there is insufficient {ml} node capacity for it to be immediately assigned to a node. The default is `false`, which means that the <> will return an error if a {ml} node with capacity to run the job cannot immediately be found. (However, this is also subject to the cluster-wide `xpack.ml.max_lazy_ml_nodes` setting - see <>.) If this option is set to `true` then the <> will not return an error, and the job will wait in the `starting` state until sufficient {ml} node capacity is available. end::allow-lazy-start[] tag::allow-no-datafeeds[] Specifies what to do when the request: + -- * Contains wildcard expressions and there are no {dfeeds} that match. * Contains the `_all` string or no identifiers and there are no matches. * Contains wildcard expressions and there are only partial matches. The default value is `true`, which returns an empty `datafeeds` array when there are no matches and the subset of results when there are partial matches. If this parameter is `false`, the request returns a `404` status code when there are no matches or only partial matches. -- end::allow-no-datafeeds[] tag::allow-no-jobs[] Specifies what to do when the request: + -- * Contains wildcard expressions and there are no jobs that match. * Contains the `_all` string or no identifiers and there are no matches. * Contains wildcard expressions and there are only partial matches. The default value is `true`, which returns an empty `jobs` array when there are no matches and the subset of results when there are partial matches. If this parameter is `false`, the request returns a `404` status code when there are no matches or only partial matches. -- end::allow-no-jobs[] tag::allow-no-match[] Specifies what to do when the request: + -- * Contains wildcard expressions and there are no {dfanalytics-jobs} that match. * Contains the `_all` string or no identifiers and there are no matches. * Contains wildcard expressions and there are only partial matches. The default value is `true`, which returns an empty `data_frame_analytics` array when there are no matches and the subset of results when there are partial matches. If this parameter is `false`, the request returns a `404` status code when there are no matches or only partial matches. -- end::allow-no-match[] tag::analysis[] Defines the type of {dfanalytics} you want to perform on your source index. For example: `outlier_detection`. See <>. end::analysis[] tag::analysis-config[] The analysis configuration, which specifies how to analyze the data. After you create a job, you cannot change the analysis configuration; all the properties are informational. end::analysis-config[] tag::analysis-limits[] Limits can be applied for the resources required to hold the mathematical models in memory. These limits are approximate and can be set per job. They do not control the memory used by other processes, for example the {es} Java processes. end::analysis-limits[] tag::analyzed-fields[] Specify `includes` and/or `excludes` patterns to select which fields will be included in the analysis. The patterns specified in `excludes` are applied last, therefore `excludes` takes precedence. In other words, if the same field is specified in both `includes` and `excludes`, then the field will not be included in the analysis. + -- The supported fields for each type of analysis are as follows: * {oldetection-cap} requires numeric or boolean data to analyze. The algorithms don't support missing values therefore fields that have data types other than numeric or boolean are ignored. Documents where included fields contain missing values, null values, or an array are also ignored. Therefore the `dest` index may contain documents that don't have an {olscore}. * {regression-cap} supports fields that are numeric, `boolean`, `text`, `keyword`, and `ip`. It is also tolerant of missing values. Fields that are supported are included in the analysis, other fields are ignored. Documents where included fields contain an array with two or more values are also ignored. Documents in the `dest` index that don’t contain a results field are not included in the {reganalysis}. * {classification-cap} supports fields that are numeric, `boolean`, `text`, `keyword`, and `ip`. It is also tolerant of missing values. Fields that are supported are included in the analysis, other fields are ignored. Documents where included fields contain an array with two or more values are also ignored. Documents in the `dest` index that don’t contain a results field are not included in the {classanalysis}. {classanalysis-cap} can be improved by mapping ordinal variable values to a single number. For example, in case of age ranges, you can model the values as ""0-14"" = 0, ""15-24"" = 1, ""25-34"" = 2, and so on. If `analyzed_fields` is not set, only the relevant fields will be included. For example, all the numeric fields for {oldetection}. For more information about field selection, see <>. -- end::analyzed-fields[] tag::analyzed-fields-excludes[] An array of strings that defines the fields that will be excluded from the analysis. You do not need to add fields with unsupported data types to `excludes`, these fields are excluded from the analysis automatically. end::analyzed-fields-excludes[] tag::analyzed-fields-includes[] An array of strings that defines the fields that will be included in the analysis. end::analyzed-fields-includes[] tag::assignment-explanation-anomaly-jobs[] For open {anomaly-jobs} only, contains messages relating to the selection of a node to run the job. end::assignment-explanation-anomaly-jobs[] tag::assignment-explanation-datafeeds[] For started {dfeeds} only, contains messages relating to the selection of a node. end::assignment-explanation-datafeeds[] tag::assignment-explanation-dfanalytics[] Contains messages relating to the selection of a node. end::assignment-explanation-dfanalytics[] tag::background-persist-interval[] Advanced configuration option. The time between each periodic persistence of the model. The default value is a randomized value between 3 to 4 hours, which avoids all jobs persisting at exactly the same time. The smallest allowed value is 1 hour. + -- TIP: For very large models (several GB), persistence could take 10-20 minutes, so do not set the `background_persist_interval` value too low. -- end::background-persist-interval[] tag::bucket-allocation-failures-count[] The number of buckets for which new entities in incoming data were not processed due to insufficient model memory. This situation is also signified by a `hard_limit: memory_status` property value. end::bucket-allocation-failures-count[] tag::bucket-count[] The number of buckets processed. end::bucket-count[] tag::bucket-count-anomaly-jobs[] The number of bucket results produced by the job. end::bucket-count-anomaly-jobs[] tag::bucket-span[] The size of the interval that the analysis is aggregated into, typically between `5m` and `1h`. The default value is `5m`. If the {anomaly-job} uses a {dfeed} with {ml-docs}/ml-configuring-aggregation.html[aggregations], this value must be divisible by the interval of the date histogram aggregation. For more information, see {ml-docs}/ml-buckets.html[Buckets]. end::bucket-span[] tag::bucket-span-results[] The length of the bucket in seconds. This value matches the `bucket_span` that is specified in the job. end::bucket-span-results[] tag::bucket-time-exponential-average[] Exponential moving average of all bucket processing times, in milliseconds. end::bucket-time-exponential-average[] tag::bucket-time-exponential-average-hour[] Exponentially-weighted moving average of bucket processing times calculated in a 1 hour time window, in milliseconds. end::bucket-time-exponential-average-hour[] tag::bucket-time-maximum[] Maximum among all bucket processing times, in milliseconds. end::bucket-time-maximum[] tag::bucket-time-minimum[] Minimum among all bucket processing times, in milliseconds. end::bucket-time-minimum[] tag::bucket-time-total[] Sum of all bucket processing times, in milliseconds. end::bucket-time-total[] tag::by-field-name[] The field used to split the data. In particular, this property is used for analyzing the splits with respect to their own history. It is used for finding unusual values in the context of the split. end::by-field-name[] tag::calendar-id[] A string that uniquely identifies a calendar. end::calendar-id[] tag::categorization-analyzer[] If `categorization_field_name` is specified, you can also define the analyzer that is used to interpret the categorization field. This property cannot be used at the same time as `categorization_filters`. The categorization analyzer specifies how the `categorization_field` is interpreted by the categorization process. The syntax is very similar to that used to define the `analyzer` in the <>. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. + The `categorization_analyzer` field can be specified either as a string or as an object. If it is a string it must refer to a <> or one added by another plugin. If it is an object it has the following properties: + .Properties of `categorization_analyzer` [%collapsible%open] ===== `char_filter`:::: (array of strings or objects) include::{docdir}/ml/ml-shared.asciidoc[tag=char-filter] `tokenizer`:::: (string or object) include::{docdir}/ml/ml-shared.asciidoc[tag=tokenizer] `filter`:::: (array of strings or objects) include::{docdir}/ml/ml-shared.asciidoc[tag=filter] ===== end::categorization-analyzer[] tag::categorization-examples-limit[] The maximum number of examples stored per category in memory and in the results data store. The default value is 4. If you increase this value, more examples are available, however it requires that you have more storage available. If you set this value to `0`, no examples are stored. + NOTE: The `categorization_examples_limit` only applies to analysis that uses categorization. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. end::categorization-examples-limit[] tag::categorization-field-name[] If this property is specified, the values of the specified field will be categorized. The resulting categories must be used in a detector by setting `by_field_name`, `over_field_name`, or `partition_field_name` to the keyword `mlcategory`. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. end::categorization-field-name[] tag::categorization-filters[] If `categorization_field_name` is specified, you can also define optional filters. This property expects an array of regular expressions. The expressions are used to filter out matching sequences from the categorization field values. You can use this functionality to fine tune the categorization by excluding sequences from consideration when categories are defined. For example, you can exclude SQL statements that appear in your log files. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. This property cannot be used at the same time as `categorization_analyzer`. If you only want to define simple regular expression filters that are applied prior to tokenization, setting this property is the easiest method. If you also want to customize the tokenizer or post-tokenization filtering, use the `categorization_analyzer` property instead and include the filters as `pattern_replace` character filters. The effect is exactly the same. end::categorization-filters[] tag::categorization-status[] The status of categorization for the job. Contains one of the following values: + -- * `ok`: Categorization is performing acceptably well (or not being used at all). * `warn`: Categorization is detecting a distribution of categories that suggests the input data is inappropriate for categorization. Problems could be that there is only one category, more than 90% of categories are rare, the number of categories is greater than 50% of the number of categorized documents, there are no frequently matched categories, or more than 50% of categories are dead. -- end::categorization-status[] tag::categorized-doc-count[] The number of documents that have had a field categorized. end::categorized-doc-count[] tag::char-filter[] One or more <>. In addition to the built-in character filters, other plugins can provide more character filters. This property is optional. If it is not specified, no character filters are applied prior to categorization. If you are customizing some other aspect of the analyzer and you need to achieve the equivalent of `categorization_filters` (which are not permitted when some other aspect of the analyzer is customized), add them here as <>. end::char-filter[] tag::compute-feature-influence[] If `true`, the feature influence calculation is enabled. Defaults to `true`. end::compute-feature-influence[] tag::chunking-config[] {dfeeds-cap} might be required to search over long time periods, for several months or years. This search is split into time chunks in order to ensure the load on {es} is managed. Chunking configuration controls how the size of these time chunks are calculated and is an advanced configuration option. + .Properties of `chunking_config` [%collapsible%open] ==== `mode`::: (string) include::{docdir}/ml/ml-shared.asciidoc[tag=mode] `time_span`::: (<>) include::{docdir}/ml/ml-shared.asciidoc[tag=time-span] ==== end::chunking-config[] tag::class-assignment-objective[] Defines the objective to optimize when assigning class labels. Available objectives are `maximize_accuracy` and `maximize_minimum_recall`. When maximizing accuracy class labels are chosen to maximize the number of correct predictions. When maximizing minimum recall labels are chosen to maximize the minimum recall for any class. Defaults to maximize_minimum_recall. end::class-assignment-objective[] tag::custom-rules[] An array of custom rule objects, which enable you to customize the way detectors operate. For example, a rule may dictate to the detector conditions under which results should be skipped. For more examples, see {ml-docs}/ml-configuring-detector-custom-rules.html[Customizing detectors with custom rules]. end::custom-rules[] tag::custom-rules-actions[] The set of actions to be triggered when the rule applies. If more than one action is specified the effects of all actions are combined. The available actions include: * `skip_result`: The result will not be created. This is the default value. Unless you also specify `skip_model_update`, the model will be updated as usual with the corresponding series value. * `skip_model_update`: The value for that series will not be used to update the model. Unless you also specify `skip_result`, the results will be created as usual. This action is suitable when certain values are expected to be consistently anomalous and they affect the model in a way that negatively impacts the rest of the results. end::custom-rules-actions[] tag::custom-rules-scope[] An optional scope of series where the rule applies. A rule must either have a non-empty scope or at least one condition. By default, the scope includes all series. Scoping is allowed for any of the fields that are also specified in `by_field_name`, `over_field_name`, or `partition_field_name`. To add a scope for a field, add the field name as a key in the scope object and set its value to an object with the following properties: end::custom-rules-scope[] tag::custom-rules-scope-filter-id[] The id of the filter to be used. end::custom-rules-scope-filter-id[] tag::custom-rules-scope-filter-type[] Either `include` (the rule applies for values in the filter) or `exclude` (the rule applies for values not in the filter). Defaults to `include`. end::custom-rules-scope-filter-type[] tag::custom-rules-conditions[] An optional array of numeric conditions when the rule applies. A rule must either have a non-empty scope or at least one condition. Multiple conditions are combined together with a logical `AND`. A condition has the following properties: end::custom-rules-conditions[] tag::custom-rules-conditions-applies-to[] Specifies the result property to which the condition applies. The available options are `actual`, `typical`, `diff_from_typical`, `time`. If your detector uses `lat_long`, `metric`, `rare`, or `freq_rare` functions, you can only specify conditions that apply to `time`. end::custom-rules-conditions-applies-to[] tag::custom-rules-conditions-operator[] Specifies the condition operator. The available options are `gt` (greater than), `gte` (greater than or equals), `lt` (less than) and `lte` (less than or equals). end::custom-rules-conditions-operator[] tag::custom-rules-conditions-value[] The value that is compared against the `applies_to` field using the `operator`. end::custom-rules-conditions-value[] tag::custom-settings[] Advanced configuration option. Contains custom meta data about the job. For example, it can contain custom URL information as shown in {ml-docs}/ml-configuring-url.html[Adding custom URLs to {ml} results]. end::custom-settings[] tag::data-description[] The data description defines the format of the input data when you send data to the job by using the <> API. Note that when configure a {dfeed}, these properties are automatically set. When data is received via the <> API, it is not stored in {es}. Only the results for {anomaly-detect} are retained. + .Properties of `data_description` [%collapsible%open] ==== `format`::: (string) Only `JSON` format is supported at this time. `time_field`::: (string) The name of the field that contains the timestamp. The default value is `time`. `time_format`::: (string) include::{docdir}/ml/ml-shared.asciidoc[tag=time-format] ==== end::data-description[] tag::data-frame-analytics[] An array of {dfanalytics-job} resources, which are sorted by the `id` value in ascending order. + .Properties of {dfanalytics-job} resources [%collapsible%open] ==== `analysis`::: (object) The type of analysis that is performed on the `source`. //Begin analyzed_fields `analyzed_fields`::: (object) Contains `includes` and/or `excludes` patterns that select which fields are included in the analysis. + .Properties of `analyzed_fields` [%collapsible%open] ===== `excludes`::: (Optional, array) An array of strings that defines the fields that are excluded from the analysis. `includes`::: (Optional, array) An array of strings that defines the fields that are included in the analysis. ===== //End analyzed_fields //Begin dest `dest`::: (string) The destination configuration of the analysis. + .Properties of `dest` [%collapsible%open] ===== `index`::: (string) The _destination index_ that stores the results of the {dfanalytics-job}. `results_field`::: (string) The name of the field that stores the results of the analysis. Defaults to `ml`. ===== //End dest `id`::: (string) The unique identifier of the {dfanalytics-job}. `model_memory_limit`::: (string) The `model_memory_limit` that has been set to the {dfanalytics-job}. `source`::: (object) The configuration of how the analysis data is sourced. It has an `index` parameter and optionally a `query` and a `_source`. + .Properties of `source` [%collapsible%open] ===== `index`::: (array) Index or indices on which to perform the analysis. It can be a single index or index pattern as well as an array of indices or patterns. `query`::: (object) The query that has been specified for the {dfanalytics-job}. The {es} query domain-specific language (<>). This value corresponds to the query object in an {es} search POST body. By default, this property has the following value: `{""match_all"": {}}`. `_source`::: (object) Contains the specified `includes` and/or `excludes` patterns that select which fields are present in the destination. Fields that are excluded cannot be included in the analysis. + .Properties of `_source` [%collapsible%open] ====== `excludes`::: (array) An array of strings that defines the fields that are excluded from the destination. `includes`::: (array) An array of strings that defines the fields that are included in the destination. ====== //End of _source ===== //End source ==== end::data-frame-analytics[] tag::data-frame-analytics-stats[] An array of statistics objects for {dfanalytics-jobs}, which are sorted by the `id` value in ascending order. //Begin analysis_stats `analysis_stats`:: (object) An object containing statistical data about the analysis. + .Properties of `analysis_stats` [%collapsible%open] ==== //Begin classification_stats `classification_stats`::: (object) An object containing statistical data about the {classanalysis}. + .Properties of `classification_stats` [%collapsible%open] ===== //Begin class_hyperparameters `hyperparameters`:::: (object) An object containing the parameters of the {classanalysis}. + .Properties of `hyperparameters` [%collapsible%open] ====== tag::dfas-alpha[] `alpha`:::: (double) Regularization factor to penalize deeper trees when training decision trees. end::dfas-alpha[] `class_assignment_objective`:::: (string) Defines whether class assignment maximizes the accuracy or the minimum recall metric. Possible values are `maximize_accuracy` and `maximize_minimum_recall`. tag::dfas-downsample-factor[] `downsample_factor`:::: (double) The value of the downsample factor. end::dfas-downsample-factor[] tag::dfas-eta[] `eta`:::: (double) The value of the eta hyperparameter. end::dfas-eta[] tag::dfas-eta-growth[] `eta_growth_rate_per_tree`:::: (double) Specifies the rate at which the `eta` increases for each new tree that is added to the forest. For example, a rate of `1.05` increases `eta` by 5%. end::dfas-eta-growth[] tag::dfas-feature-bag-fraction[] `feature_bag_fraction`:::: (double) The fraction of features that is used when selecting a random bag for each candidate split. end::dfas-feature-bag-fraction[] tag::dfas-gamma[] `gamma`:::: (double) Regularization factor to penalize trees with large numbers of nodes. end::dfas-gamma[] tag::dfas-lambda[] `lambda`:::: (double) Regularization factor to penalize large leaf weights. end::dfas-lambda[] tag::dfas-max-attempts[] `max_attempts_to_add_tree`:::: (integer) If the algorithm fails to determine a non-trivial tree (more than a single leaf), this parameter determines how many of such consecutive failures are tolerated. Once the number of attempts exceeds the threshold, the forest training stops. end::dfas-max-attempts[] tag::dfas-max-optimization-rounds[] `max_optimization_rounds_per_hyperparameter`:::: (integer) A multiplier responsible for determining the maximum number of hyperparameter optimization steps in the Bayesian optimization procedure. The maximum number of steps is determined based on the number of undefined hyperparameters times the maximum optimization rounds per hyperparameter. end::dfas-max-optimization-rounds[] tag::dfas-max-trees[] `max_trees`:::: (integer) The maximum number of trees in the forest. end::dfas-max-trees[] tag::dfas-num-folds[] `num_folds`:::: (integer) The maximum number of folds for the cross-validation procedure. end::dfas-num-folds[] tag::dfas-num-splits[] `num_splits_per_feature`:::: (integer) Determines the maximum number of splits for every feature that can occur in a decision tree when the tree is trained. end::dfas-num-splits[] tag::dfas-soft-limit[] `soft_tree_depth_limit`:::: (double) Tree depth limit is used for calculating the tree depth penalty. This is a soft limit, it can be exceeded. end::dfas-soft-limit[] tag::dfas-soft-tolerance[] `soft_tree_depth_tolerance`:::: (double) Tree depth tolerance is used for calculating the tree depth penalty. This is a soft limit, it can be exceeded. end::dfas-soft-tolerance[] ====== //End class_hyperparameters tag::dfas-iteration[] `iteration`:::: (integer) The number of iterations on the analysis. end::dfas-iteration[] tag::dfas-timestamp[] `timestamp`:::: (date) The timestamp when the statistics were reported in milliseconds since the epoch. end::dfas-timestamp[] //Begin class_timing_stats tag::dfas-timing-stats[] `timing_stats`:::: (object) An object containing time statistics about the {dfanalytics-job}. end::dfas-timing-stats[] + .Properties of `timing_stats` [%collapsible%open] ====== tag::dfas-timing-stats-elapsed[] `elapsed_time`:::: (integer) Runtime of the analysis in milliseconds. end::dfas-timing-stats-elapsed[] tag::dfas-timing-stats-iteration[] `iteration_time`:::: (integer) Runtime of the latest iteration of the analysis in milliseconds. end::dfas-timing-stats-iteration[] ====== //End class_timing_stats //Begin class_validation_loss tag::dfas-validation-loss[] `validation_loss`:::: (object) An object containing information about validation loss. end::dfas-validation-loss[] + .Properties of `validation_loss` [%collapsible%open] ====== tag::dfas-validation-loss-type[] `loss_type`:::: (string) The type of the loss metric. For example, `binomial_logistic`. end::dfas-validation-loss-type[] tag::dfas-validation-loss-fold[] `fold_values`:::: (array of strings) Validation loss values for every added decision tree during the forest growing procedure. end::dfas-validation-loss-fold[] ====== //End class_validation_loss ===== //End classification_stats //Begin outlier_detection_stats `outlier_detection_stats`::: (object) An object containing statistical data about the {oldetection} job. + .Properties of `outlier_detection_stats` [%collapsible%open] ===== //Begin parameters `parameters`:::: (object) The list of job parameters specified by the user or determined by algorithmic heuristics. + .Properties of `parameters` [%collapsible%open] ====== `compute_feature_influence`:::: (boolean) If true, feature influence calculation is enabled. `feature_influence_threshold`:::: (double) The minimum {olscore} that a document needs to have to calculate its feature influence score. `method`:::: (string) The method that {oldetection} uses. Possible values are `lof`, `ldof`, `distance_kth_nn`, `distance_knn`, and `ensemble`. `n_neighbors`:::: (integer) The value for how many nearest neighbors each method of {oldetection} uses to calculate its outlier score. `outlier_fraction`:::: (double) The proportion of the data set that is assumed to be outlying prior to {oldetection}. `standardization_enabled`:::: (boolean) If true, then the following operation is performed on the columns before computing {olscores}: (x_i - mean(x_i)) / sd(x_i). ====== //End parameters include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timestamp] //Begin od_timing_stats include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timing-stats] + .Property of `timing_stats` [%collapsible%open] ====== include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timing-stats-elapsed] ====== //End od_timing_stats ===== //End outlier_detection_stats //Begin regression_stats `regression_stats`::: (object) An object containing statistical data about the {reganalysis}. + .Properties of `regression_stats` [%collapsible%open] ===== //Begin reg_hyperparameters `hyperparameters`:::: (object) An object containing the parameters of the {reganalysis}. + .Properties of `hyperparameters` [%collapsible%open] ====== include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-alpha] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-downsample-factor] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-eta] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-eta-growth] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-feature-bag-fraction] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-gamma] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-lambda] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-max-attempts] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-max-optimization-rounds] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-max-trees] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-num-folds] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-num-splits] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-soft-limit] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-soft-tolerance] ====== //End reg_hyperparameters include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-iteration] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timestamp] //Begin reg_timing_stats include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timing-stats] + .Propertis of `timing_stats` [%collapsible%open] ====== include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timing-stats-elapsed] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-timing-stats-iteration] ====== //End reg_timing_stats //Begin reg_validation_loss include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-validation-loss] + .Properties of `validation_loss` [%collapsible%open] ====== include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-validation-loss-type] include::{docdir}/ml/ml-shared.asciidoc[tag=dfas-validation-loss-fold] ====== //End reg_validation_loss ===== //End regression_stats ==== //End analysis_stats `assignment_explanation`::: (string) For running jobs only, contains messages relating to the selection of a node to run the job. `id`::: (string) The unique identifier of the {dfanalytics-job}. `memory_usage`::: (Optional, object) An object describing memory usage of the analytics. It is present only after the job is started and memory usage is reported. `memory_usage`.`peak_usage_bytes`::: (long) The number of bytes used at the highest peak of memory usage. `memory_usage`.`timestamp`::: (date) The timestamp when memory usage was calculated. `node`::: (object) Contains properties for the node that runs the job. This information is available only for running jobs. `node`.`attributes`::: (object) Lists node attributes such as `ml.machine_memory`, `ml.max_open_jobs`, and `xpack.installed`. `node`.`ephemeral_id`::: (string) The ephemeral id of the node. `node`.`id`::: (string) The unique identifier of the node. `node`.`name`::: (string) The node name. `node`.`transport_address`::: (string) The host and port where transport HTTP connections are accepted. `progress`::: (array) The progress report of the {dfanalytics-job} by phase. `progress`.`phase`::: (string) Defines the phase of the {dfanalytics-job}. Possible phases: `reindexing`, `loading_data`, `analyzing`, and `writing_results`. `progress`.`progress_percent`::: (integer) The progress that the {dfanalytics-job} has made expressed in percentage. `state`::: (string) Current state of the {dfanalytics-job}. end::data-frame-analytics-stats[] tag::datafeed-id[] A numerical character string that uniquely identifies the {dfeed}. This identifier can contain lowercase alphanumeric characters (a-z and 0-9), hyphens, and underscores. It must start and end with alphanumeric characters. end::datafeed-id[] tag::datafeed-id-wildcard[] Identifier for the {dfeed}. It can be a {dfeed} identifier or a wildcard expression. end::datafeed-id-wildcard[] tag::dead-category-count[] The number of categories created by categorization that will never be assigned again because another category's definition makes it a superset of the dead category. (Dead categories are a side effect of the way categorization has no prior training.) end::dead-category-count[] tag::decompress-definition[] Specifies whether the included model definition should be returned as a JSON map (`true`) or in a custom compressed format (`false`). Defaults to `true`. end::decompress-definition[] tag::delayed-data-check-config[] Specifies whether the {dfeed} checks for missing data and the size of the window. For example: `{""enabled"": true, ""check_window"": ""1h""}`. + The {dfeed} can optionally search over indices that have already been read in an effort to determine whether any data has subsequently been added to the index. If missing data is found, it is a good indication that the `query_delay` option is set too low and the data is being indexed after the {dfeed} has passed that moment in time. See {ml-docs}/ml-delayed-data-detection.html[Working with delayed data]. + This check runs only on real-time {dfeeds}. + .Properties of `delayed_data_check_config` [%collapsible%open] ==== `check_window`:: (<>) The window of time that is searched for late data. This window of time ends with the latest finalized bucket. It defaults to `null`, which causes an appropriate `check_window` to be calculated when the real-time {dfeed} runs. In particular, the default `check_window` span calculation is based on the maximum of `2h` or `8 * bucket_span`. `enabled`:: (boolean) Specifies whether the {dfeed} periodically checks for delayed data. Defaults to `true`. ==== end::delayed-data-check-config[] tag::dependent-variable[] Defines which field of the document is to be predicted. This parameter is supplied by field name and must match one of the fields in the index being used to train. If this field is missing from a document, then that document will not be used for training, but a prediction with the trained model will be generated for it. It is also known as continuous target variable. end::dependent-variable[] tag::desc-results[] If true, the results are sorted in descending order. end::desc-results[] tag::description-dfa[] A description of the job. end::description-dfa[] tag::dest[] The destination configuration, consisting of `index` and optionally `results_field` (`ml` by default). + .Properties of `dest` [%collapsible%open] ==== `index`::: (Required, string) Defines the _destination index_ to store the results of the {dfanalytics-job}. `results_field`::: (Optional, string) Defines the name of the field in which to store the results of the analysis. Defaults to `ml`. ==== end::dest[] tag::detector-description[] A description of the detector. For example, `Low event rate`. end::detector-description[] tag::detector-field-name[] The field that the detector uses in the function. If you use an event rate function such as `count` or `rare`, do not specify this field. + -- NOTE: The `field_name` cannot contain double quotes or backslashes. -- end::detector-field-name[] tag::detector-index[] A unique identifier for the detector. This identifier is based on the order of the detectors in the `analysis_config`, starting at zero. end::detector-index[] tag::earliest-record-timestamp[] The timestamp of the earliest chronologically input document. end::earliest-record-timestamp[] tag::empty-bucket-count[] The number of buckets which did not contain any data. If your data contains many empty buckets, consider increasing your `bucket_span` or using functions that are tolerant to gaps in data such as `mean`, `non_null_sum` or `non_zero_count`. end::empty-bucket-count[] tag::eta[] Advanced configuration option. The shrinkage applied to the weights. Smaller values result in larger forests which have better generalization error. However, the smaller the value the longer the training will take. For more information about shrinkage, see https://en.wikipedia.org/wiki/Gradient_boosting#Shrinkage[this wiki article]. end::eta[] tag::exclude-frequent[] Contains one of the following values: `all`, `none`, `by`, or `over`. If set, frequent entities are excluded from influencing the anomaly results. Entities can be considered frequent over time or frequent in a population. If you are working with both over and by fields, then you can set `exclude_frequent` to `all` for both fields, or to `by` or `over` for those specific fields. end::exclude-frequent[] tag::exclude-interim-results[] If `true`, the output excludes interim results. By default, interim results are included. end::exclude-interim-results[] tag::feature-bag-fraction[] Advanced configuration option. Defines the fraction of features that will be used when selecting a random bag for each candidate split. end::feature-bag-fraction[] tag::feature-influence-threshold[] The minimum {olscore} that a document needs to have in order to calculate its {fiscore}. Value range: 0-1 (`0.1` by default). end::feature-influence-threshold[] tag::field-selection[] An array of objects that explain selection for each field, sorted by the field names. + .Properties of `field_selection` objects [%collapsible%open] ==== `is_included`::: (boolean) Whether the field is selected to be included in the analysis. `is_required`::: (boolean) Whether the field is required. `feature_type`::: (string) The feature type of this field for the analysis. May be `categorical` or `numerical`. `mapping_types`::: (string) The mapping types of the field. `name`::: (string) The field name. `reason`::: (string) The reason a field is not selected to be included in the analysis. ==== end::field-selection[] tag::filter[] One or more <>. In addition to the built-in token filters, other plugins can provide more token filters. This property is optional. If it is not specified, no token filters are applied prior to categorization. end::filter[] tag::filter-id[] A string that uniquely identifies a filter. end::filter-id[] tag::forecast-total[] The number of individual forecasts currently available for the job. A value of `1` or more indicates that forecasts exist. end::forecast-total[] tag::frequency[] The interval at which scheduled queries are made while the {dfeed} runs in real time. The default value is either the bucket span for short bucket spans, or, for longer bucket spans, a sensible fraction of the bucket span. For example: `150s`. When `frequency` is shorter than the bucket span, interim results for the last (partial) bucket are written then eventually overwritten by the full bucket results. If the {dfeed} uses aggregations, this value must be divisible by the interval of the date histogram aggregation. end::frequency[] tag::frequent-category-count[] The number of categories that match more than 1% of categorized documents. end::frequent-category-count[] tag::from[] Skips the specified number of {dfanalytics-jobs}. The default value is `0`. end::from[] tag::function[] The analysis function that is used. For example, `count`, `rare`, `mean`, `min`, `max`, and `sum`. For more information, see {ml-docs}/ml-functions.html[Function reference]. end::function[] tag::gamma[] Advanced configuration option. Regularization parameter to prevent overfitting on the training dataset. Multiplies a linear penalty associated with the size of individual trees in the forest. The higher the value the more training will prefer smaller trees. The smaller this parameter the larger individual trees will be and the longer train will take. end::gamma[] tag::groups[] A list of job groups. A job can belong to no groups or many. end::groups[] tag::include-model-definition[] Specifies if the model definition should be returned in the response. Defaults to `false`. When `true`, only a single model must match the ID patterns provided, otherwise a bad request is returned. end::include-model-definition[] tag::indices[] An array of index names. Wildcards are supported. For example: `[""it_ops_metrics"", ""server*""]`. + -- NOTE: If any indices are in remote clusters then `node.remote_cluster_client` must not be set to `false` on any {ml} nodes. -- end::indices[] tag::indices-options[] Specifies index expansion options that are used during search. + -- For example: ``` { ""expand_wildcards"": [""all""], ""ignore_unavailable"": true, ""allow_no_indices"": ""false"", ""ignore_throttled"": true } ``` For more information about these options, see <>. -- end::indices-options[] tag::influencers[] A comma separated list of influencer field names. Typically these can be the by, over, or partition fields that are used in the detector configuration. You might also want to use a field name that is not specifically named in a detector, but is available as part of the input data. When you use multiple detectors, the use of influencers is recommended as it aggregates results for each influencer entity. end::influencers[] tag::input-bytes[] The number of bytes of input data posted to the {anomaly-job}. end::input-bytes[] tag::input-field-count[] The total number of fields in input documents posted to the {anomaly-job}. This count includes fields that are not used in the analysis. However, be aware that if you are using a {dfeed}, it extracts only the required fields from the documents it retrieves before posting them to the job. end::input-field-count[] tag::input-record-count[] The number of input documents posted to the {anomaly-job}. end::input-record-count[] tag::invalid-date-count[] The number of input documents with either a missing date field or a date that could not be parsed. end::invalid-date-count[] tag::is-interim[] If `true`, this is an interim result. In other words, the results are calculated based on partial input data. end::is-interim[] tag::job-id-anomaly-detection[] Identifier for the {anomaly-job}. end::job-id-anomaly-detection[] tag::job-id-data-frame-analytics[] Identifier for the {dfanalytics-job}. end::job-id-data-frame-analytics[] tag::job-id-anomaly-detection-default[] Identifier for the {anomaly-job}. It can be a job identifier, a group name, or a wildcard expression. If you do not specify one of these options, the API returns information for all {anomaly-jobs}. end::job-id-anomaly-detection-default[] tag::job-id-data-frame-analytics-default[] Identifier for the {dfanalytics-job}. If you do not specify this option, the API returns information for the first hundred {dfanalytics-jobs}. end::job-id-data-frame-analytics-default[] tag::job-id-anomaly-detection-list[] An identifier for the {anomaly-jobs}. It can be a job identifier, a group name, or a comma-separated list of jobs or groups. end::job-id-anomaly-detection-list[] tag::job-id-anomaly-detection-wildcard[] Identifier for the {anomaly-job}. It can be a job identifier, a group name, or a wildcard expression. end::job-id-anomaly-detection-wildcard[] tag::job-id-anomaly-detection-wildcard-list[] Identifier for the {anomaly-job}. It can be a job identifier, a group name, a comma-separated list of jobs or groups, or a wildcard expression. end::job-id-anomaly-detection-wildcard-list[] tag::job-id-anomaly-detection-define[] Identifier for the {anomaly-job}. This identifier can contain lowercase alphanumeric characters (a-z and 0-9), hyphens, and underscores. It must start and end with alphanumeric characters. end::job-id-anomaly-detection-define[] tag::job-id-data-frame-analytics-define[] Identifier for the {dfanalytics-job}. This identifier can contain lowercase alphanumeric characters (a-z and 0-9), hyphens, and underscores. It must start and end with alphanumeric characters. end::job-id-data-frame-analytics-define[] tag::job-id-datafeed[] The unique identifier for the job to which the {dfeed} sends data. end::job-id-datafeed[] tag::lambda[] Advanced configuration option. Regularization parameter to prevent overfitting on the training dataset. Multiplies an L2 regularisation term which applies to leaf weights of the individual trees in the forest. The higher the value the more training will attempt to keep leaf weights small. This makes the prediction function smoother at the expense of potentially not being able to capture relevant relationships between the features and the {depvar}. The smaller this parameter the larger individual trees will be and the longer train will take. end::lambda[] tag::last-data-time[] The timestamp at which data was last analyzed, according to server time. end::last-data-time[] tag::latency[] The size of the window in which to expect data that is out of time order. The default value is 0 (no latency). If you specify a non-zero value, it must be greater than or equal to one second. For more information about time units, see <>. + -- NOTE: Latency is only applicable when you send data by using the <> API. -- end::latency[] tag::latest-empty-bucket-timestamp[] The timestamp of the last bucket that did not contain any data. end::latest-empty-bucket-timestamp[] tag::latest-record-timestamp[] The timestamp of the latest chronologically input document. end::latest-record-timestamp[] tag::latest-sparse-record-timestamp[] The timestamp of the last bucket that was considered sparse. end::latest-sparse-record-timestamp[] tag::max-empty-searches[] If a real-time {dfeed} has never seen any data (including during any initial training period) then it will automatically stop itself and close its associated job after this many real-time searches that return no documents. In other words, it will stop after `frequency` times `max_empty_searches` of real-time operation. If not set then a {dfeed} with no end time that sees no data will remain started until it is explicitly stopped. By default this setting is not set. end::max-empty-searches[] tag::max-trees[] Advanced configuration option. Defines the maximum number of trees the forest is allowed to contain. The maximum value is 2000. end::max-trees[] tag::memory-estimation[] An object containing the memory estimates. + .Properties of `memory_estimation` [%collapsible%open] ==== `expected_memory_with_disk`::: (string) Estimated memory usage under the assumption that overflowing to disk is allowed during {dfanalytics}. `expected_memory_with_disk` is usually smaller than `expected_memory_without_disk` as using disk allows to limit the main memory needed to perform {dfanalytics}. `expected_memory_without_disk`::: (string) Estimated memory usage under the assumption that the whole {dfanalytics} should happen in memory (i.e. without overflowing to disk). ==== end::memory-estimation[] tag::method[] Sets the method that {oldetection} uses. If the method is not set {oldetection} uses an ensemble of different methods and normalises and combines their individual {olscores} to obtain the overall {olscore}. We recommend to use the ensemble method. Available methods are `lof`, `ldof`, `distance_kth_nn`, `distance_knn`. end::method[] tag::missing-field-count[] The number of input documents that are missing a field that the {anomaly-job} is configured to analyze. Input documents with missing fields are still processed because it is possible that not all fields are missing. + -- NOTE: If you are using {dfeeds} or posting data to the job in JSON format, a high `missing_field_count` is often not an indication of data issues. It is not necessarily a cause for concern. -- end::missing-field-count[] tag::mode[] There are three available modes: + -- * `auto`: The chunk size is dynamically calculated. This is the default and recommended value. * `manual`: Chunking is applied according to the specified `time_span`. * `off`: No chunking is applied. -- end::mode[] tag::model-bytes[] The number of bytes of memory used by the models. This is the maximum value since the last time the model was persisted. If the job is closed, this value indicates the latest size. end::model-bytes[] tag::model-bytes-exceeded[] The number of bytes over the high limit for memory usage at the last allocation failure. end::model-bytes-exceeded[] tag::model-id[] The unique identifier of the trained {infer} model. end::model-id[] tag::model-memory-limit[] The approximate maximum amount of memory resources that are required for analytical processing. Once this limit is approached, data pruning becomes more aggressive. Upon exceeding this limit, new entities are not modeled. The default value for jobs created in version 6.1 and later is `1024mb`. This value will need to be increased for jobs that are expected to analyze high cardinality fields, but the default is set to a relatively small size to ensure that high resource usage is a conscious decision. The default value for jobs created in versions earlier than 6.1 is `4096mb`. + If you specify a number instead of a string, the units are assumed to be MiB. Specifying a string is recommended for clarity. If you specify a byte size unit of `b` or `kb` and the number does not equate to a discrete number of megabytes, it is rounded down to the closest MiB. The minimum valid value is 1 MiB. If you specify a value less than 1 MiB, an error occurs. For more information about supported byte size units, see <>. + If your `elasticsearch.yml` file contains an `xpack.ml.max_model_memory_limit` setting, an error occurs when you try to create jobs that have `model_memory_limit` values greater than that setting. For more information, see <>. end::model-memory-limit[] tag::model-memory-limit-anomaly-jobs[] The upper limit for model memory usage, checked on increasing values. end::model-memory-limit-anomaly-jobs[] tag::model-memory-limit-dfa[] The approximate maximum amount of memory resources that are permitted for analytical processing. The default value for {dfanalytics-jobs} is `1gb`. If your `elasticsearch.yml` file contains an `xpack.ml.max_model_memory_limit` setting, an error occurs when you try to create {dfanalytics-jobs} that have `model_memory_limit` values greater than that setting. For more information, see <>. end::model-memory-limit-dfa[] tag::model-memory-status[] The status of the mathematical models, which can have one of the following values: + -- * `ok`: The models stayed below the configured value. * `soft_limit`: The models used more than 60% of the configured memory limit and older unused models will be pruned to free up space. * `hard_limit`: The models used more space than the configured memory limit. As a result, not all incoming data was processed. -- end::model-memory-status[] tag::model-plot-config[] This advanced configuration option stores model information along with the results. It provides a more detailed view into {anomaly-detect}. + -- WARNING: If you enable model plot it can add considerable overhead to the performance of the system; it is not feasible for jobs with many entities. Model plot provides a simplified and indicative view of the model and its bounds. It does not display complex features such as multivariate correlations or multimodal data. As such, anomalies may occasionally be reported which cannot be seen in the model plot. Model plot config can be configured when the job is created or updated later. It must be disabled if performance issues are experienced. -- end::model-plot-config[] tag::model-plot-config-enabled[] If true, enables calculation and storage of the model bounds for each entity that is being analyzed. By default, this is not enabled. end::model-plot-config-enabled[] tag::model-plot-config-terms[] Limits data collection to this comma separated list of partition or by field values. If terms are not specified or it is an empty string, no filtering is applied. For example, ""CPU,NetworkIn,DiskWrites"". Wildcards are not supported. Only the specified `terms` can be viewed when using the Single Metric Viewer. end::model-plot-config-terms[] tag::model-snapshot-id[] A numerical character string that uniquely identifies the model snapshot. For example, `1575402236000 `. end::model-snapshot-id[] tag::model-snapshot-retention-days[] Advanced configuration option. The period of time (in days) that model snapshots are retained. Age is calculated relative to the timestamp of the newest model snapshot. The default value is `1`, which means snapshots that are one day (twenty-four hours) older than the newest snapshot are deleted. end::model-snapshot-retention-days[] tag::model-timestamp[] The timestamp of the last record when the model stats were gathered. end::model-timestamp[] tag::multivariate-by-fields[] This functionality is reserved for internal use. It is not supported for use in customer environments and is not subject to the support SLA of official GA features. + -- If set to `true`, the analysis will automatically find correlations between metrics for a given `by` field value and report anomalies when those correlations cease to hold. For example, suppose CPU and memory usage on host A is usually highly correlated with the same metrics on host B. Perhaps this correlation occurs because they are running a load-balanced application. If you enable this property, then anomalies will be reported when, for example, CPU usage on host A is high and the value of CPU usage on host B is low. That is to say, you'll see an anomaly when the CPU of host A is unusual given the CPU of host B. NOTE: To use the `multivariate_by_fields` property, you must also specify `by_field_name` in your detector. -- end::multivariate-by-fields[] tag::n-neighbors[] Defines the value for how many nearest neighbors each method of {oldetection} will use to calculate its {olscore}. When the value is not set, different values will be used for different ensemble members. This helps improve diversity in the ensemble. Therefore, only override this if you are confident that the value you choose is appropriate for the data set. end::n-neighbors[] tag::node-address[] The network address of the node. end::node-address[] tag::node-datafeeds[] For started {dfeeds} only, this information pertains to the node upon which the {dfeed} is started. end::node-datafeeds[] tag::node-ephemeral-id[] The ephemeral ID of the node. end::node-ephemeral-id[] tag::node-id[] The unique identifier of the node. end::node-id[] tag::node-jobs[] Contains properties for the node that runs the job. This information is available only for open jobs. end::node-jobs[] tag::num-top-classes[] Defines the number of categories for which the predicted probabilities are reported. It must be non-negative. If it is greater than the total number of categories (in the {version} version of the {stack}, it's two) to predict then we will report all category probabilities. Defaults to 2. end::num-top-classes[] tag::open-time[] For open jobs only, the elapsed time for which the job has been open. end::open-time[] tag::out-of-order-timestamp-count[] The number of input documents that are out of time sequence and outside of the latency window. This information is applicable only when you provide data to the {anomaly-job} by using the <>. These out of order documents are discarded, since jobs require time series data to be in ascending chronological order. end::out-of-order-timestamp-count[] tag::outlier-fraction[] Sets the proportion of the data set that is assumed to be outlying prior to {oldetection}. For example, 0.05 means it is assumed that 5% of values are real outliers and 95% are inliers. end::outlier-fraction[] tag::over-field-name[] The field used to split the data. In particular, this property is used for analyzing the splits with respect to the history of all splits. It is used for finding unusual values in the population of all splits. For more information, see {ml-docs}/ml-configuring-pop.html[Performing population analysis]. end::over-field-name[] tag::partition-field-name[] The field used to segment the analysis. When you use this property, you have completely independent baselines for each value of this field. end::partition-field-name[] tag::prediction-field-name[] Defines the name of the prediction field in the results. Defaults to `_prediction`. end::prediction-field-name[] tag::processed-field-count[] The total number of fields in all the documents that have been processed by the {anomaly-job}. Only fields that are specified in the detector configuration object contribute to this count. The timestamp is not included in this count. end::processed-field-count[] tag::processed-record-count[] The number of input documents that have been processed by the {anomaly-job}. This value includes documents with missing fields, since they are nonetheless analyzed. If you use {dfeeds} and have aggregations in your search query, the `processed_record_count` is the number of aggregation results processed, not the number of {es} documents. end::processed-record-count[] tag::randomize-seed[] Defines the seed to the random generator that is used to pick which documents will be used for training. By default it is randomly generated. Set it to a specific value to ensure the same documents are used for training assuming other related parameters (for example, `source`, `analyzed_fields`, etc.) are the same. end::randomize-seed[] tag::query[] The {es} query domain-specific language (DSL). This value corresponds to the query object in an {es} search POST body. All the options that are supported by {es} can be used, as this object is passed verbatim to {es}. By default, this property has the following value: `{""match_all"": {""boost"": 1}}`. end::query[] tag::query-delay[] The number of seconds behind real time that data is queried. For example, if data from 10:04 a.m. might not be searchable in {es} until 10:06 a.m., set this property to 120 seconds. The default value is randomly selected between `60s` and `120s`. This randomness improves the query performance when there are multiple jobs running on the same node. For more information, see {ml-docs}/ml-delayed-data-detection.html[Handling delayed data]. end::query-delay[] tag::rare-category-count[] The number of categories that match just one categorized document. end::rare-category-count[] tag::renormalization-window-days[] Advanced configuration option. The period over which adjustments to the score are applied, as new data is seen. The default value is the longer of 30 days or 100 `bucket_spans`. end::renormalization-window-days[] tag::results-index-name[] A text string that affects the name of the {ml} results index. The default value is `shared`, which generates an index named `.ml-anomalies-shared`. end::results-index-name[] tag::results-retention-days[] Advanced configuration option. The period of time (in days) that results are retained. Age is calculated relative to the timestamp of the latest bucket result. If this property has a non-null value, once per day at 00:30 (server time), results that are the specified number of days older than the latest bucket result are deleted from {es}. The default value is null, which means all results are retained. end::results-retention-days[] tag::retain[] If `true`, this snapshot will not be deleted during automatic cleanup of snapshots older than `model_snapshot_retention_days`. However, this snapshot will be deleted when the job is deleted. The default value is `false`. end::retain[] tag::script-fields[] Specifies scripts that evaluate custom expressions and returns script fields to the {dfeed}. The detector configuration objects in a job can contain functions that use these script fields. For more information, see {ml-docs}/ml-configuring-transform.html[Transforming data with script fields] and <>. end::script-fields[] tag::scroll-size[] The `size` parameter that is used in {es} searches. The default value is `1000`. end::scroll-size[] tag::search-bucket-avg[] The average search time per bucket, in milliseconds. end::search-bucket-avg[] tag::search-count[] The number of searches run by the {dfeed}. end::search-count[] tag::search-exp-avg-hour[] The exponential average search time per hour, in milliseconds. end::search-exp-avg-hour[] tag::search-time[] The total time the {dfeed} spent searching, in milliseconds. end::search-time[] tag::size[] Specifies the maximum number of {dfanalytics-jobs} to obtain. The default value is `100`. end::size[] tag::snapshot-id[] Identifier for the model snapshot. end::snapshot-id[] tag::source-put-dfa[] The configuration of how to source the analysis data. It requires an `index`. Optionally, `query` and `_source` may be specified. + .Properties of `source` [%collapsible%open] ==== `index`::: (Required, string or array) Index or indices on which to perform the analysis. It can be a single index or index pattern as well as an array of indices or patterns. + WARNING: If your source indices contain documents with the same IDs, only the document that is indexed last appears in the destination index. `query`::: (Optional, object) The {es} query domain-specific language (<>). This value corresponds to the query object in an {es} search POST body. All the options that are supported by {es} can be used, as this object is passed verbatim to {es}. By default, this property has the following value: `{""match_all"": {}}`. `_source`::: (Optional, object) Specify `includes` and/or `excludes` patterns to select which fields will be present in the destination. Fields that are excluded cannot be included in the analysis. + .Properties of `_source` [%collapsible%open] ===== `includes`:::: (array) An array of strings that defines the fields that will be included in the destination. `excludes`:::: (array) An array of strings that defines the fields that will be excluded from the destination. ===== ==== end::source-put-dfa[] tag::sparse-bucket-count[] The number of buckets that contained few data points compared to the expected number of data points. If your data contains many sparse buckets, consider using a longer `bucket_span`. end::sparse-bucket-count[] tag::standardization-enabled[] If `true`, then the following operation is performed on the columns before computing outlier scores: (x_i - mean(x_i)) / sd(x_i). Defaults to `true`. For more information, see https://en.wikipedia.org/wiki/Feature_scaling#Standardization_(Z-score_Normalization)[this wiki page about standardization]. end::standardization-enabled[] tag::state-anomaly-job[] The status of the {anomaly-job}, which can be one of the following values: + -- * `closed`: The job finished successfully with its model state persisted. The job must be opened before it can accept further data. * `closing`: The job close action is in progress and has not yet completed. A closing job cannot accept further data. * `failed`: The job did not finish successfully due to an error. This situation can occur due to invalid input data, a fatal error occurring during the analysis, or an external interaction such as the process being killed by the Linux out of memory (OOM) killer. If the job had irrevocably failed, it must be force closed and then deleted. If the {dfeed} can be corrected, the job can be closed and then re-opened. * `opened`: The job is available to receive and process data. * `opening`: The job open action is in progress and has not yet completed. -- end::state-anomaly-job[] tag::state-datafeed[] The status of the {dfeed}, which can be one of the following values: + -- * `starting`: The {dfeed} has been requested to start but has not yet started. * `started`: The {dfeed} is actively receiving data. * `stopping`: The {dfeed} has been requested to stop gracefully and is completing its final action. * `stopped`: The {dfeed} is stopped and will not receive data until it is re-started. -- end::state-datafeed[] tag::summary-count-field-name[] If this property is specified, the data that is fed to the job is expected to be pre-summarized. This property value is the name of the field that contains the count of raw data points that have been summarized. The same `summary_count_field_name` applies to all detectors in the job. + -- NOTE: The `summary_count_field_name` property cannot be used with the `metric` function. -- end::summary-count-field-name[] tag::tags[] A comma delimited string of tags. A {infer} model can have many tags, or none. When supplied, only {infer} models that contain all the supplied tags are returned. end::tags[] tag::timeout-start[] Controls the amount of time to wait until the {dfanalytics-job} starts. Defaults to 20 seconds. end::timeout-start[] tag::timeout-stop[] Controls the amount of time to wait until the {dfanalytics-job} stops. Defaults to 20 seconds. end::timeout-stop[] tag::time-format[] The time format, which can be `epoch`, `epoch_ms`, or a custom pattern. The default value is `epoch`, which refers to UNIX or Epoch time (the number of seconds since 1 Jan 1970). The value `epoch_ms` indicates that time is measured in milliseconds since the epoch. The `epoch` and `epoch_ms` time formats accept either integer or real values. + + NOTE: Custom patterns must conform to the Java `DateTimeFormatter` class. When you use date-time formatting patterns, it is recommended that you provide the full date, time and time zone. For example: `yyyy-MM-dd'T'HH:mm:ssX`. If the pattern that you specify is not sufficient to produce a complete timestamp, job creation fails. end::time-format[] tag::time-span[] The time span that each search will be querying. This setting is only applicable when the mode is set to `manual`. For example: `3h`. end::time-span[] tag::timestamp-results[] The start time of the bucket for which these results were calculated. end::timestamp-results[] tag::tokenizer[] The name or definition of the <> to use after character filters are applied. This property is compulsory if `categorization_analyzer` is specified as an object. Machine learning provides a tokenizer called `ml_classic` that tokenizes in the same way as the non-customizable tokenizer in older versions of the product. If you want to use that tokenizer but change the character or token filters, specify `""tokenizer"": ""ml_classic""` in your `categorization_analyzer`. end::tokenizer[] tag::total-by-field-count[] The number of `by` field values that were analyzed by the models. This value is cumulative for all detectors in the job. end::total-by-field-count[] tag::total-category-count[] The number of categories created by categorization. end::total-category-count[] tag::total-over-field-count[] The number of `over` field values that were analyzed by the models. This value is cumulative for all detectors in the job. end::total-over-field-count[] tag::total-partition-field-count[] The number of `partition` field values that were analyzed by the models. This value is cumulative for all detectors in the job. end::total-partition-field-count[] tag::trained-model-configs[] An array of trained model resources, which are sorted by the `model_id` value in ascending order. + .Properties of trained model resources [%collapsible%open] ==== `created_by`::: (string) Information on the creator of the trained model. `create_time`::: (<>) The time when the trained model was created. `default_field_map` ::: (object) A string to string object that contains the default field map to use when inferring against the model. For example, data frame analytics may train the model on a specific multi-field `foo.keyword`. The analytics job would then supply a default field map entry for `""foo"" : ""foo.keyword""`. + Any field map described in the inference configuration takes precedence. `estimated_heap_memory_usage_bytes`::: (integer) The estimated heap usage in bytes to keep the trained model in memory. `estimated_operations`::: (integer) The estimated number of operations to use the trained model. `license_level`::: (string) The license level of the trained model. `metadata`::: (object) An object containing metadata about the trained model. For example, models created by {dfanalytics} contain `analysis_config` and `input` objects. `model_id`::: (string) Idetifier for the trained model. `tags`::: (string) A comma delimited string of tags. A {infer} model can have many tags, or none. `version`::: (string) The {es} version number in which the trained model was created. ==== end::trained-model-configs[] tag::training-percent[] Defines what percentage of the eligible documents that will be used for training. Documents that are ignored by the analysis (for example those that contain arrays with more than one value) won’t be included in the calculation for used percentage. Defaults to `100`. end::training-percent[] tag::use-null[] Defines whether a new series is used as the null series when there is no value for the by or partition fields. The default value is `false`. end::use-null[] ",16274,True,3329.4376258728985,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, ANSI SQL parsing mode is enabled. */ public boolean ansi = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE database (IF NOT EXISTS)? db=errorCapturingIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH DBPROPERTIES tablePropertyList))* #createDatabase | ALTER database db=errorCapturingIdentifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | ALTER database db=errorCapturingIdentifier SET locationSpec #setDatabaseLocation | DROP database (IF EXISTS)? db=errorCapturingIdentifier (RESTRICT | CASCADE)? #dropDatabase | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE multipartIdentifier RENAME COLUMN from=qualifiedName TO to=identifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=qualifiedNameList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=qualifiedNameList #dropTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE multipartIdentifier (ALTER | CHANGE) COLUMN? qualifiedName (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE tableIdentifier partitionSpec? CHANGE COLUMN? colName=errorCapturingIdentifier colType colPosition? #changeColumn | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER TABLE tableIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER VIEW tableIdentifier ADD (IF NOT EXISTS)? partitionSpec+ #addTablePartition | ALTER TABLE tableIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER TABLE tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER VIEW tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* #dropTablePartitions | ALTER TABLE multipartIdentifier SET locationSpec #setTableLocation | ALTER TABLE tableIdentifier partitionSpec SET locationSpec #setPartitionLocation | ALTER TABLE tableIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW tableIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? qualifiedName AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? qualifiedName #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=errorCapturingIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) tableIdentifier ((FROM | IN) db=errorCapturingIdentifier)? #showColumns | SHOW PARTITIONS tableIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (qualifiedName | pattern=STRING))? #showFunctions | SHOW CREATE TABLE tableIdentifier #showCreateTable | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) database EXTENDED? db=errorCapturingIdentifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE tableIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE tableIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? tableIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE tableIdentifier partitionSpec? #loadData | TRUNCATE TABLE tableIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING qualifiedName ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assign (',' assign)* ; assign : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | IDENTIFIER '->' expression #lambda | '(' IDENTIFIER (',' IDENTIFIER)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : {ansi}? INTERVAL? intervalField+ | {!ansi}? INTERVAL intervalField* ; intervalField : value=intervalValue unit=intervalUnit (TO to=intervalUnit)? ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER qualifiedName ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=qualifiedName dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!ansi}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {ansi}? ansiNonReserved #unquotedIdentifier | {!ansi}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `spark.sql.ansi.enabled=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `spark.sql.ansi.enabled=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `spark.sql.ansi.enabled=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12041,False,2242.1822330074274,median "// tag::HeaderFullDisplayName[] = repo.Index_ColumList - V // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--antorareferencedlist: :ExistsProperty--antorareferencinglist: :ExistsProperty--has_execution_plan_issue: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--referencedobjectlist: :ExistsProperty--sql_modules_definition: :ExistsProperty--FK: :ExistsProperty--AntoraIndexList: :ExistsProperty--Columns: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] 6890291C-9D61-EB11-84DC-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] repo.Index_ColumList // end::RepoObject_FullDisplayName2[] == SysObject_type // tag::SysObject_type[] V // end::SysObject_type[] == SysObject_type_name // tag::SysObject_type_name[] view // end::SysObject_type_name[] == SysObject_id // tag::SysObject_id[] 948914452 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-09-10 11:15:39 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] [discrete] == _ [#column-antoraindexcolumnlist] === AntoraIndexColumnList [cols=""d,8a,m,m,m""] |=== | |AntoraIndexColumnList |nvarchar(max) |NULL | |=== .Referencing Columns -- * xref:repo.index_columlist_t.adoc#column-antoraindexcolumnlist[+repo.Index_ColumList_T.AntoraIndexColumnList+] -- [#column-columnlist] === ColumnList [cols=""d,8a,m,m,m""] |=== | |ColumnList |nvarchar(max) |NULL | |=== .Referencing Columns -- * xref:repo.index_columlist_t.adoc#column-columnlist[+repo.Index_ColumList_T.ColumnList+] -- [#column-constraintcolumnlist] === ConstraintColumnList [cols=""d,8a,m,m,m""] |=== | |ConstraintColumnList |nvarchar(max) |NULL | |=== .Referencing Columns -- * xref:repo.index_columlist_t.adoc#column-constraintcolumnlist[+repo.Index_ColumList_T.ConstraintColumnList+] -- [#column-dbmlindexcolumnlist] === DbmlIndexColumnList [cols=""d,8a,m,m,m""] |=== | |DbmlIndexColumnList |nvarchar(max) |NULL | |=== .Referencing Columns -- * xref:repo.index_columlist_t.adoc#column-dbmlindexcolumnlist[+repo.Index_ColumList_T.DbmlIndexColumnList+] -- [#column-indexunderlineguid] === index_guid [cols=""d,8a,m,m,m""] |=== | |index_guid |uniqueidentifier |NOT NULL | |=== .Referenced Columns -- * xref:repo.indexcolumn_union_t.adoc#column-indexunderlineguid[+repo.IndexColumn_union_T.index_guid+] -- .Referencing Columns -- * xref:repo.index_columlist_t.adoc#column-indexunderlineguid[+repo.Index_ColumList_T.index_guid+] -- [#column-persistencewherecolumnlist] === PersistenceWhereColumnList [cols=""d,8a,m,m,m""] |=== | |PersistenceWhereColumnList |nvarchar(max) |NULL | |=== .Referencing Columns -- * xref:repo.index_columlist_t.adoc#column-persistencewherecolumnlist[+repo.Index_ColumList_T.PersistenceWhereColumnList+] -- [#column-pumlindexcolumnlist] === PumlIndexColumnList [cols=""d,8a,m,m,m""] |=== | |PumlIndexColumnList |nvarchar(max) |NULL | |=== .Referencing Columns -- * xref:repo.index_columlist_t.adoc#column-pumlindexcolumnlist[+repo.Index_ColumList_T.PumlIndexColumnList+] -- // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] | |<> |nvarchar(max) |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(max) |NULL | | |<> |uniqueidentifier |NOT NULL | | |<> |nvarchar(max) |NULL | | |<> |nvarchar(max) |NULL | // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] [#index-idxunderlineindexunderlinecolumlistunderlineunderline1] === idx_Index_ColumList++__++1 * IndexSemanticGroup: xref:other/indexsemanticgroup.adoc#startbnoblankgroupendb[no_group] + -- * <>; uniqueidentifier -- * PK, Unique, Real: 0, 0, 0 // end::AntoraIndexList[] == AntoraMeasureDetails // tag::AntoraMeasureDetails[] // end::AntoraMeasureDetails[] == AntoraMeasureDescriptions == AntoraParameterList // tag::AntoraParameterList[] // end::AntoraParameterList[] == AntoraXrefCulturesList // tag::AntoraXrefCulturesList[] * xref:dhw:sqldb:repo.index_columlist.adoc[] - // end::AntoraXrefCulturesList[] == cultures_count // tag::cultures_count[] 1 // end::cultures_count[] == Other tags source: property.RepoObjectProperty_cross As rop_cross === additional_reference_csv // tag::additional_reference_csv[] // end::additional_reference_csv[] === AdocUspSteps // tag::adocuspsteps[] // end::adocuspsteps[] === AntoraReferencedList // tag::antorareferencedlist[] * xref:dhw:sqldb:repo.indexcolumn_union_t.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:repo.index_columlist_t.adoc[] * xref:dhw:sqldb:repo.usp_persist_index_columlist_t.adoc[] // end::antorareferencinglist[] === Description // tag::description[] // end::description[] === exampleUsage // tag::exampleusage[] // end::exampleusage[] === exampleUsage_2 // tag::exampleusage_2[] // end::exampleusage_2[] === exampleUsage_3 // tag::exampleusage_3[] // end::exampleusage_3[] === exampleUsage_4 // tag::exampleusage_4[] // end::exampleusage_4[] === exampleUsage_5 // tag::exampleusage_5[] // end::exampleusage_5[] === exampleWrong_Usage // tag::examplewrong_usage[] // end::examplewrong_usage[] === has_execution_plan_issue // tag::has_execution_plan_issue[] 1 // end::has_execution_plan_issue[] === has_get_referenced_issue // tag::has_get_referenced_issue[] // end::has_get_referenced_issue[] === has_history // tag::has_history[] // end::has_history[] === has_history_columns // tag::has_history_columns[] // end::has_history_columns[] === InheritanceType // tag::inheritancetype[] // end::inheritancetype[] === is_persistence // tag::is_persistence[] // end::is_persistence[] === is_persistence_check_duplicate_per_pk // tag::is_persistence_check_duplicate_per_pk[] // end::is_persistence_check_duplicate_per_pk[] === is_persistence_check_for_empty_source // tag::is_persistence_check_for_empty_source[] // end::is_persistence_check_for_empty_source[] === is_persistence_delete_changed // tag::is_persistence_delete_changed[] // end::is_persistence_delete_changed[] === is_persistence_delete_missing // tag::is_persistence_delete_missing[] // end::is_persistence_delete_missing[] === is_persistence_insert // tag::is_persistence_insert[] // end::is_persistence_insert[] === is_persistence_truncate // tag::is_persistence_truncate[] // end::is_persistence_truncate[] === is_persistence_update_changed // tag::is_persistence_update_changed[] // end::is_persistence_update_changed[] === is_repo_managed // tag::is_repo_managed[] 0 // end::is_repo_managed[] === is_ssas // tag::is_ssas[] 0 // end::is_ssas[] === microsoft_database_tools_support // tag::microsoft_database_tools_support[] // end::microsoft_database_tools_support[] === MS_Description // tag::ms_description[] // end::ms_description[] === persistence_source_RepoObject_fullname // tag::persistence_source_repoobject_fullname[] // end::persistence_source_repoobject_fullname[] === persistence_source_RepoObject_fullname2 // tag::persistence_source_repoobject_fullname2[] // end::persistence_source_repoobject_fullname2[] === persistence_source_RepoObject_guid // tag::persistence_source_repoobject_guid[] // end::persistence_source_repoobject_guid[] === persistence_source_RepoObject_xref // tag::persistence_source_repoobject_xref[] // end::persistence_source_repoobject_xref[] === pk_index_guid // tag::pk_index_guid[] // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] * [repo].[IndexColumn_union_T] // end::referencedobjectlist[] === usp_persistence_RepoObject_guid // tag::usp_persistence_repoobject_guid[] // end::usp_persistence_repoobject_guid[] === UspExamples // tag::uspexamples[] // end::uspexamples[] === uspgenerator_usp_id // tag::uspgenerator_usp_id[] // end::uspgenerator_usp_id[] === UspParameters // tag::uspparameters[] // end::uspparameters[] == Boolean Attributes source: property.RepoObjectProperty WHERE property_int = 1 // tag::boolean_attributes[] :has_execution_plan_issue: // end::boolean_attributes[] == PlantUML diagrams === PlantUML Entity // tag::puml_entity[] [plantuml, entity-{docname}, svg, subs=macros] .... 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:repo.index_columlist.adoc[]"" as repo.Index_ColumList << V >> { AntoraIndexColumnList : (nvarchar(max)) ColumnList : (nvarchar(max)) ConstraintColumnList : (nvarchar(max)) DbmlIndexColumnList : (nvarchar(max)) - index_guid : (uniqueidentifier) PersistenceWhereColumnList : (nvarchar(max)) PumlIndexColumnList : (nvarchar(max)) -- } .... // end::puml_entity[] === PlantUML Entity 1 1 FK // tag::puml_entity_1_1_fk[] [plantuml, entity_1_1_fk-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:repo.index_columlist.adoc[]"" as repo.Index_ColumList << V >> { - idx_Index_ColumList__1 .. index_guid; uniqueidentifier } footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_fk[] === PlantUML 1 1 ObjectRef // tag::puml_entity_1_1_objectref[] [plantuml, entity_1_1_objectref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:repo.index_columlist.adoc[]"" as repo.Index_ColumList << V >> { -- } entity ""puml-link:dhw:sqldb:repo.index_columlist_t.adoc[]"" as repo.Index_ColumList_T << U >> { - **index_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_union_t.adoc[]"" as repo.IndexColumn_union_T << U >> { **index_guid** : (uniqueidentifier) - **index_column_id** : (int) -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_index_columlist_t.adoc[]"" as repo.usp_PERSIST_Index_ColumList_T << P >> { -- } repo.Index_ColumList <.. repo.Index_ColumList_T repo.Index_ColumList <.. repo.usp_PERSIST_Index_ColumList_T repo.IndexColumn_union_T <.. repo.Index_ColumList footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_objectref[] === PlantUML 30 0 ObjectRef // tag::puml_entity_30_0_objectref[] [plantuml, entity_30_0_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:config.ftv_dwh_database.adoc[]"" as config.ftv_dwh_database << IF >> { -- } entity ""puml-link:dhw:sqldb:config.ftv_get_parameter_value.adoc[]"" as config.ftv_get_parameter_value << IF >> { -- } entity ""puml-link:dhw:sqldb:config.parameter.adoc[]"" as config.Parameter << U >> { - **Parameter_name** : (varchar(100)) - **sub_Parameter** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:configt.parameter_default.adoc[]"" as configT.Parameter_default << V >> { - **Parameter_name** : (varchar(52)) - **sub_Parameter** : (nvarchar(26)) -- } entity ""puml-link:dhw:sqldb:property.external_repoobjectproperty.adoc[]"" as property.external_RepoObjectProperty << U >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject.adoc[]"" as property.PropertyName_RepoObject << V >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject_t.adoc[]"" as property.PropertyName_RepoObject_T << U >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty.adoc[]"" as property.RepoObjectProperty << U >> { - **RepoObjectProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_src.adoc[]"" as property.RepoObjectProperty_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_tgt.adoc[]"" as property.RepoObjectProperty_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_selectedpropertyname_split.adoc[]"" as property.RepoObjectProperty_SelectedPropertyName_split << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference.adoc[]"" as reference.additional_Reference << U >> { - **Id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_src.adoc[]"" as reference.additional_Reference_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_tgt.adoc[]"" as reference.additional_Reference_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_src.adoc[]"" as reference.additional_Reference_from_ssas_src << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_tgt.adoc[]"" as reference.additional_Reference_from_ssas_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_is_external.adoc[]"" as reference.additional_Reference_is_external << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object.adoc[]"" as reference.additional_Reference_Object << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object_t.adoc[]"" as reference.additional_Reference_Object_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_objectcolumn.adoc[]"" as reference.additional_Reference_ObjectColumn << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) **ColumnName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_objectcolumn_t.adoc[]"" as reference.additional_Reference_ObjectColumn_T << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_src.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_tgt.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:repo.index_columlist.adoc[]"" as repo.Index_ColumList << V >> { -- } entity ""puml-link:dhw:sqldb:repo.index_ssas.adoc[]"" as repo.Index_ssas << V >> { - **databasename** : (nvarchar(128)) **index_name** : (nvarchar(450)) -- } entity ""puml-link:dhw:sqldb:repo.index_ssas_t.adoc[]"" as repo.Index_ssas_T << U >> { - **databasename** : (nvarchar(128)) **index_name** : (nvarchar(450)) -- } entity ""puml-link:dhw:sqldb:repo.index_virtual.adoc[]"" as repo.Index_virtual << U >> { - **index_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_ssas.adoc[]"" as repo.IndexColumn_ssas << V >> { - **index_guid** : (uniqueidentifier) - **index_column_id** : (int) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_ssas_gross.adoc[]"" as repo.IndexColumn_ssas_gross << V >> { -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_ssas_t.adoc[]"" as repo.IndexColumn_ssas_T << U >> { - **index_guid** : (uniqueidentifier) - **index_column_id** : (int) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_union.adoc[]"" as repo.IndexColumn_union << V >> { **index_guid** : (uniqueidentifier) - **index_column_id** : (int) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_union_t.adoc[]"" as repo.IndexColumn_union_T << U >> { **index_guid** : (uniqueidentifier) - **index_column_id** : (int) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_virtual.adoc[]"" as repo.IndexColumn_virtual << U >> { - **index_guid** : (uniqueidentifier) - **index_column_id** : (int) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_virtual_gross.adoc[]"" as repo.IndexColumn_virtual_gross << V >> { - **index_column_id** : (int) -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_src.adoc[]"" as repo.RepoObject_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_tgt.adoc[]"" as repo.RepoObject_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_src.adoc[]"" as repo.RepoObject_SSAS_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_tgt.adoc[]"" as repo.RepoObject_SSAS_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn.adoc[]"" as repo.RepoObjectColumn << U >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_external_src.adoc[]"" as repo.RepoObjectColumn_external_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_external_tgt.adoc[]"" as repo.RepoObjectColumn_external_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_ssas_src.adoc[]"" as repo.RepoObjectColumn_SSAS_src << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobjectcolumn_ssas_tgt.adoc[]"" as repo.RepoObjectColumn_SSAS_tgt << V >> { - **RepoObjectColumn_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema.adoc[]"" as repo.RepoSchema << U >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_src.adoc[]"" as repo.RepoSchema_ssas_src << V >> { - **RepoSchema_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_tgt.adoc[]"" as repo.RepoSchema_ssas_tgt << V >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.syscolumn_repoobjectcolumn_via_name.adoc[]"" as repo.SysColumn_RepoObjectColumn_via_name << V >> { -- } entity ""puml-link:dhw:sqldb:repo.sysobject_repoobject_via_name.adoc[]"" as repo.SysObject_RepoObject_via_name << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.extendedproperties.adoc[]"" as repo_sys.ExtendedProperties << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.indexcolumn_unique.adoc[]"" as repo_sys.IndexColumn_unique << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.syscolumn.adoc[]"" as repo_sys.SysColumn << V >> { -- } entity ""puml-link:dhw:sqldb:repo_sys.sysobject.adoc[]"" as repo_sys.SysObject << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.additional_reference_step1.adoc[]"" as ssas.additional_Reference_step1 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.indexcolumn_from_iskey.adoc[]"" as ssas.IndexColumn_from_IsKey << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.indexcolumn_from_isunique.adoc[]"" as ssas.IndexColumn_from_IsUnique << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.indexcolumn_from_relationship.adoc[]"" as ssas.IndexColumn_from_Relationship << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.indexcolumn_union.adoc[]"" as ssas.IndexColumn_union << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json.adoc[]"" as ssas.model_json << U >> { - **databasename** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_10.adoc[]"" as ssas.model_json_10 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_20.adoc[]"" as ssas.model_json_20 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_201_descriptions_multiline.adoc[]"" as ssas.model_json_201_descriptions_multiline << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_2011_descriptions_stragg.adoc[]"" as ssas.model_json_2011_descriptions_StrAgg << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables.adoc[]"" as ssas.model_json_31_tables << V >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables_t.adoc[]"" as ssas.model_json_31_tables_T << U >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[]"" as ssas.model_json_311_tables_columns << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[]"" as ssas.model_json_311_tables_columns_T << U >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313_tables_partitions.adoc[]"" as ssas.model_json_313_tables_partitions << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131_tables_partitions_source.adoc[]"" as ssas.model_json_3131_tables_partitions_source << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) **tables_partitions_source_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311_tables_partitions_source_posfrom.adoc[]"" as ssas.model_json_31311_tables_partitions_source_PosFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313111_tables_partitions_source_stringfrom.adoc[]"" as ssas.model_json_313111_tables_partitions_source_StringFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131111_tables_partitions_source_posdot.adoc[]"" as ssas.model_json_3131111_tables_partitions_source_PosDot << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311111_tables_partitions_source_part123.adoc[]"" as ssas.model_json_31311111_tables_partitions_source_Part123 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_32_relationships.adoc[]"" as ssas.model_json_32_relationships << V >> { - **databasename** : (nvarchar(128)) **relationships_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_32_relationships_t.adoc[]"" as ssas.model_json_32_relationships_T << U >> { - **ForeignKey_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources.adoc[]"" as ssas.model_json_33_dataSources << V >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources_t.adoc[]"" as ssas.model_json_33_dataSources_T << U >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:sys_dwh.columns.adoc[]"" as sys_dwh.columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.computed_columns.adoc[]"" as sys_dwh.computed_columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.default_constraints.adoc[]"" as sys_dwh.default_constraints << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.extended_properties.adoc[]"" as sys_dwh.extended_properties << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.identity_columns.adoc[]"" as sys_dwh.identity_columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.index_columns.adoc[]"" as sys_dwh.index_columns << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.indexes.adoc[]"" as sys_dwh.indexes << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.objects.adoc[]"" as sys_dwh.objects << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.parameters.adoc[]"" as sys_dwh.parameters << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.schemas.adoc[]"" as sys_dwh.schemas << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.sql_modules.adoc[]"" as sys_dwh.sql_modules << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.tables.adoc[]"" as sys_dwh.tables << SN >> { -- } entity ""puml-link:dhw:sqldb:sys_dwh.types.adoc[]"" as sys_dwh.types << SN >> { -- } config.ftv_dwh_database <.. repo_sys.ExtendedProperties config.ftv_dwh_database <.. repo_sys.SysColumn config.ftv_get_parameter_value <.. ssas.additional_Reference_step1 config.ftv_get_parameter_value <.. reference.additional_Reference_is_external config.ftv_get_parameter_value <.. repo.RepoObject_external_src config.Parameter <.. property.PropertyName_RepoObject config.Parameter <.. config.ftv_get_parameter_value config.Parameter <.. config.ftv_dwh_database configT.Parameter_default <.. config.Parameter property.external_RepoObjectProperty <.. property.RepoObjectProperty_external_src property.PropertyName_RepoObject <.. property.PropertyName_RepoObject_T property.PropertyName_RepoObject_T <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty <.. property.PropertyName_RepoObject property.RepoObjectProperty <.. property.RepoObjectProperty_SelectedPropertyName_split property.RepoObjectProperty_external_src <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty_external_tgt <.. property.RepoObjectProperty property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_from_properties_src property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_wo_columns_from_properties_src reference.additional_Reference <.. reference.additional_Reference_is_external reference.additional_Reference_from_properties_src <.. reference.additional_Reference_from_properties_tgt reference.additional_Reference_from_properties_tgt <.. reference.additional_Reference reference.additional_Reference_from_ssas_src <.. reference.additional_Reference_from_ssas_tgt reference.additional_Reference_from_ssas_tgt <.. reference.additional_Reference reference.additional_Reference_is_external <.. reference.additional_Reference_ObjectColumn reference.additional_Reference_is_external <.. reference.additional_Reference_Object reference.additional_Reference_Object <.. reference.additional_Reference_Object_T reference.additional_Reference_Object_T <.. repo.RepoObject_external_src reference.additional_Reference_Object_T <.. repo.RepoObjectColumn_external_src reference.additional_Reference_ObjectColumn <.. reference.additional_Reference_ObjectColumn_T reference.additional_Reference_ObjectColumn_T <.. repo.RepoObjectColumn_external_src reference.additional_Reference_wo_columns_from_properties_src <.. reference.additional_Reference_wo_columns_from_properties_tgt reference.additional_Reference_wo_columns_from_properties_tgt <.. reference.additional_Reference repo.Index_ssas <.. repo.Index_ssas_T repo.Index_ssas_T <.. repo.IndexColumn_ssas repo.Index_ssas_T <.. repo.IndexColumn_ssas_gross repo.Index_virtual <.. repo.IndexColumn_virtual_gross repo.IndexColumn_ssas <.. repo.IndexColumn_ssas_T repo.IndexColumn_ssas_gross <.. repo.IndexColumn_union repo.IndexColumn_ssas_T <.. repo.IndexColumn_ssas_gross repo.IndexColumn_union <.. repo.IndexColumn_union_T repo.IndexColumn_union_T <.. repo.Index_ColumList repo.IndexColumn_virtual <.. repo.IndexColumn_virtual_gross repo.IndexColumn_virtual_gross <.. repo.IndexColumn_union repo.RepoObject <.. repo.SysObject_RepoObject_via_name repo.RepoObject <.. repo.SysColumn_RepoObjectColumn_via_name repo.RepoObject <.. repo.IndexColumn_virtual_gross repo.RepoObject <.. repo.IndexColumn_ssas_gross repo.RepoObject <.. repo.RepoObjectColumn_external_src repo.RepoObject <.. property.RepoObjectProperty_external_tgt repo.RepoObject <.. repo.RepoObject_external_src repo.RepoObject_external_src <.. repo.RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.RepoObject repo.RepoObject_external_tgt <.. repo.RepoObjectColumn_external_tgt repo.RepoObject_SSAS_src <.. repo.RepoObject_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObjectColumn_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObject repo.RepoObjectColumn <.. repo.IndexColumn_ssas_gross repo.RepoObjectColumn <.. repo.IndexColumn_virtual_gross repo.RepoObjectColumn <.. repo.SysColumn_RepoObjectColumn_via_name repo.RepoObjectColumn_external_src <.. repo.RepoObjectColumn_external_tgt repo.RepoObjectColumn_external_tgt <.. repo.RepoObjectColumn repo.RepoObjectColumn_SSAS_src <.. repo.RepoObjectColumn_SSAS_tgt repo.RepoObjectColumn_SSAS_tgt <.. repo.RepoObjectColumn repo.RepoSchema <.. repo.RepoObject_SSAS_src repo.RepoSchema_ssas_src <.. repo.RepoSchema_ssas_tgt repo.RepoSchema_ssas_tgt <.. repo.RepoSchema repo.SysColumn_RepoObjectColumn_via_name <.. repo_sys.IndexColumn_unique repo.SysObject_RepoObject_via_name <.. repo_sys.IndexColumn_unique repo_sys.ExtendedProperties <.. repo_sys.SysObject repo_sys.ExtendedProperties <.. repo_sys.SysColumn repo_sys.IndexColumn_unique <.. repo.IndexColumn_union repo_sys.SysColumn <.. repo.SysColumn_RepoObjectColumn_via_name repo_sys.SysObject <.. repo.SysObject_RepoObject_via_name repo_sys.SysObject <.. repo_sys.SysColumn ssas.additional_Reference_step1 <.. reference.additional_Reference_from_ssas_src ssas.IndexColumn_from_IsKey <.. ssas.IndexColumn_union ssas.IndexColumn_from_IsUnique <.. ssas.IndexColumn_union ssas.IndexColumn_from_Relationship <.. ssas.IndexColumn_union ssas.IndexColumn_union <.. repo.IndexColumn_ssas ssas.IndexColumn_union <.. repo.Index_ssas ssas.model_json <.. ssas.model_json_10 ssas.model_json_10 <.. ssas.model_json_20 ssas.model_json_20 <.. repo.RepoSchema_ssas_src ssas.model_json_20 <.. ssas.model_json_32_relationships ssas.model_json_20 <.. ssas.model_json_201_descriptions_multiline ssas.model_json_20 <.. ssas.model_json_33_dataSources ssas.model_json_20 <.. ssas.model_json_31_tables ssas.model_json_201_descriptions_multiline <.. ssas.model_json_2011_descriptions_StrAgg ssas.model_json_2011_descriptions_StrAgg <.. repo.RepoSchema_ssas_src ssas.model_json_31_tables <.. ssas.model_json_31_tables_T ssas.model_json_31_tables_T <.. ssas.model_json_311_tables_columns ssas.model_json_31_tables_T <.. repo.RepoObject_SSAS_src ssas.model_json_31_tables_T <.. ssas.model_json_313_tables_partitions ssas.model_json_311_tables_columns <.. ssas.model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. repo.RepoObjectColumn_SSAS_src ssas.model_json_311_tables_columns_T <.. ssas.IndexColumn_from_Relationship ssas.model_json_311_tables_columns_T <.. ssas.IndexColumn_from_IsUnique ssas.model_json_311_tables_columns_T <.. ssas.IndexColumn_from_IsKey ssas.model_json_311_tables_columns_T <.. ssas.additional_Reference_step1 ssas.model_json_313_tables_partitions <.. ssas.model_json_3131_tables_partitions_source ssas.model_json_3131_tables_partitions_source <.. ssas.model_json_31311_tables_partitions_source_PosFrom ssas.model_json_31311_tables_partitions_source_PosFrom <.. ssas.model_json_313111_tables_partitions_source_StringFrom ssas.model_json_313111_tables_partitions_source_StringFrom <.. ssas.model_json_3131111_tables_partitions_source_PosDot ssas.model_json_3131111_tables_partitions_source_PosDot <.. ssas.model_json_31311111_tables_partitions_source_Part123 ssas.model_json_31311111_tables_partitions_source_Part123 <.. ssas.additional_Reference_step1 ssas.model_json_32_relationships <.. ssas.model_json_32_relationships_T ssas.model_json_32_relationships_T <.. ssas.IndexColumn_from_Relationship ssas.model_json_33_dataSources <.. ssas.model_json_33_dataSources_T ssas.model_json_33_dataSources_T <.. ssas.additional_Reference_step1 sys_dwh.columns <.. repo_sys.ExtendedProperties sys_dwh.columns <.. repo_sys.SysColumn sys_dwh.computed_columns <.. repo_sys.SysColumn sys_dwh.default_constraints <.. repo_sys.SysColumn sys_dwh.extended_properties <.. repo_sys.ExtendedProperties sys_dwh.identity_columns <.. repo_sys.SysColumn sys_dwh.index_columns <.. repo_sys.IndexColumn_unique sys_dwh.indexes <.. repo_sys.ExtendedProperties sys_dwh.indexes <.. repo_sys.IndexColumn_unique sys_dwh.objects <.. repo_sys.SysObject sys_dwh.objects <.. repo_sys.ExtendedProperties sys_dwh.parameters <.. repo_sys.ExtendedProperties sys_dwh.schemas <.. repo_sys.SysObject sys_dwh.schemas <.. repo_sys.ExtendedProperties sys_dwh.sql_modules <.. repo_sys.SysObject sys_dwh.tables <.. repo_sys.SysObject sys_dwh.types <.. repo_sys.SysColumn footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_30_0_objectref[] === PlantUML 0 30 ObjectRef // tag::puml_entity_0_30_objectref[] [plantuml, entity_0_30_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:docs.antoranavlistpage_by_schema.adoc[]"" as docs.AntoraNavListPage_by_schema << V >> { -- } entity ""puml-link:dhw:sqldb:docs.antorapage_indexsemanticgroup.adoc[]"" as docs.AntoraPage_IndexSemanticGroup << V >> { - **page_content** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:docs.foreignkey_relationscript.adoc[]"" as docs.ForeignKey_RelationScript << V >> { **referenced_RepoObject_guid** : (uniqueidentifier) **referencing_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:docs.ftv_repoobject_reference_plantuml_entityreflist.adoc[]"" as docs.ftv_RepoObject_Reference_PlantUml_EntityRefList << IF >> { -- } entity ""puml-link:dhw:sqldb:docs.indexsemanticgroup.adoc[]"" as docs.IndexSemanticgroup << V >> { -- } entity ""puml-link:dhw:sqldb:docs.indexsemanticgrouppatterndatatype.adoc[]"" as docs.IndexSemanticgroupPatterndatatype << V >> { **IndexSemanticGroup** : (nvarchar(512)) **IndexPatternColumnDatatype** : (nvarchar(4000)) -- } entity ""puml-link:dhw:sqldb:docs.objectrefcyclic.adoc[]"" as docs.ObjectRefCyclic << V >> { -- } entity ""puml-link:dhw:sqldb:docs.objectrefcyclic_entitylist.adoc[]"" as docs.ObjectRefCyclic_EntityList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_adoc.adoc[]"" as docs.RepoObject_Adoc << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_adoc_t.adoc[]"" as docs.RepoObject_Adoc_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_indexlist.adoc[]"" as docs.RepoObject_IndexList << V >> { **RepoObject_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_indexlist_t.adoc[]"" as docs.RepoObject_IndexList_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml.adoc[]"" as docs.RepoObject_Plantuml << V >> { - **RepoObject_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_entity.adoc[]"" as docs.RepoObject_Plantuml_Entity << V >> { -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_entity_t.adoc[]"" as docs.RepoObject_Plantuml_Entity_T << U >> { - **RepoObject_guid** : (uniqueidentifier) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_fkreflist.adoc[]"" as docs.RepoObject_PlantUml_FkRefList << V >> { **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_pumlentityfklist.adoc[]"" as docs.RepoObject_PlantUml_PumlEntityFkList << V >> { **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:docs.repoobject_plantuml_t.adoc[]"" as docs.RepoObject_Plantuml_T << U >> { - **RepoObject_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.schema_entitylist.adoc[]"" as docs.Schema_EntityList << V >> { - **RepoObject_schema_name** : (nvarchar(128)) - **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.schema_puml.adoc[]"" as docs.Schema_puml << V >> { - **RepoSchema_guid** : (uniqueidentifier) **cultures_name** : (nvarchar(10)) -- } entity ""puml-link:dhw:sqldb:docs.schema_pumlpartial_fkreflist.adoc[]"" as docs.Schema_PumlPartial_FkRefList << V >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport.adoc[]"" as docs.usp_AntoraExport << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport_objectpartialscontent.adoc[]"" as docs.usp_AntoraExport_ObjectPartialsContent << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_antoraexport_objectpuml.adoc[]"" as docs.usp_AntoraExport_ObjectPuml << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_adoc_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Adoc_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_indexlist_t.adoc[]"" as docs.usp_PERSIST_RepoObject_IndexList_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_plantuml_entity_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Plantuml_Entity_T << P >> { -- } entity ""puml-link:dhw:sqldb:docs.usp_persist_repoobject_plantuml_t.adoc[]"" as docs.usp_PERSIST_RepoObject_Plantuml_T << P >> { -- } entity ""puml-link:dhw:sqldb:reference.ftv_repoobject_columreferencerepoobject.adoc[]"" as reference.ftv_RepoObject_ColumReferenceRepoObject << IF >> { -- } entity ""puml-link:dhw:sqldb:repo.foreignkey_gross.adoc[]"" as repo.ForeignKey_gross << V >> { -- } entity ""puml-link:dhw:sqldb:repo.foreignkey_indexes.adoc[]"" as repo.ForeignKey_Indexes << V >> { -- } entity ""puml-link:dhw:sqldb:repo.foreignkey_indexes_union.adoc[]"" as repo.ForeignKey_Indexes_union << V >> { **ForeignKey_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.foreignkey_indexes_union_t.adoc[]"" as repo.ForeignKey_Indexes_union_T << U >> { **ForeignKey_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.foreignkey_virtual_indexes.adoc[]"" as repo.ForeignKey_virtual_Indexes << V >> { -- } entity ""puml-link:dhw:sqldb:repo.index_columlist.adoc[]"" as repo.Index_ColumList << V >> { -- } entity ""puml-link:dhw:sqldb:repo.index_columlist_t.adoc[]"" as repo.Index_ColumList_T << U >> { - **index_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.index_gross.adoc[]"" as repo.Index_gross << V >> { -- } entity ""puml-link:dhw:sqldb:repo.index_sqlconstraint_pkuq.adoc[]"" as repo.Index_SqlConstraint_PkUq << V >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_related_fk_union.adoc[]"" as repo.RepoObject_related_FK_union << V >> { **RepoObject_guid** : (uniqueidentifier) **included_RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_sqlcreatetable.adoc[]"" as repo.RepoObject_SqlCreateTable << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.usp_index_finish.adoc[]"" as repo.usp_Index_finish << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_index_foreignkey.adoc[]"" as repo.usp_Index_ForeignKey << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_index_inheritance.adoc[]"" as repo.usp_index_inheritance << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_index_virtual_set.adoc[]"" as repo.usp_Index_virtual_set << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_main.adoc[]"" as repo.usp_main << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_foreignkey_indexes_union_t.adoc[]"" as repo.usp_PERSIST_ForeignKey_Indexes_union_T << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_index_columlist_t.adoc[]"" as repo.usp_PERSIST_Index_ColumList_T << P >> { -- } entity ""puml-link:dhw:sqldb:uspgenerator.generatoruspstep_persistence_src.adoc[]"" as uspgenerator.GeneratorUspStep_Persistence_src << V >> { - **usp_id** : (int) -- } entity ""puml-link:dhw:sqldb:uspgenerator.usp_generatorusp_insert_update_persistence.adoc[]"" as uspgenerator.usp_GeneratorUsp_insert_update_persistence << P >> { -- } docs.ftv_RepoObject_Reference_PlantUml_EntityRefList <.. docs.RepoObject_Plantuml docs.IndexSemanticgroup <.. docs.AntoraPage_IndexSemanticGroup docs.IndexSemanticgroupPatterndatatype <.. docs.IndexSemanticgroup docs.ObjectRefCyclic_EntityList <.. docs.ObjectRefCyclic docs.RepoObject_Adoc <.. docs.usp_PERSIST_RepoObject_Adoc_T docs.RepoObject_Adoc <.. docs.RepoObject_Adoc_T docs.REpoObject_Adoc_T <.. docs.usp_PERSIST_RepoObject_Adoc_T docs.RepoObject_IndexList <.. docs.RepoObject_IndexList_T docs.RepoObject_IndexList <.. docs.usp_PERSIST_RepoObject_IndexList_T docs.RepoObject_IndexList_T <.. docs.RepoObject_Adoc docs.RepoObject_IndexList_T <.. docs.RepoObject_Plantuml_Entity docs.RepoObject_IndexList_T <.. docs.usp_PERSIST_RepoObject_IndexList_T docs.RepoObject_Plantuml <.. docs.RepoObject_Plantuml_T docs.RepoObject_Plantuml <.. docs.usp_PERSIST_RepoObject_Plantuml_T docs.RepoObject_Plantuml_Entity <.. docs.usp_PERSIST_RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity <.. docs.RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity_T <.. docs.RepoObject_Adoc docs.RepoObject_Plantuml_Entity_T <.. docs.ftv_RepoObject_Reference_PlantUml_EntityRefList docs.RepoObject_Plantuml_Entity_T <.. docs.usp_PERSIST_RepoObject_Plantuml_Entity_T docs.RepoObject_Plantuml_Entity_T <.. docs.Schema_EntityList docs.RepoObject_Plantuml_Entity_T <.. docs.ObjectRefCyclic_EntityList docs.RepoObject_Plantuml_Entity_T <.. docs.RepoObject_PlantUml_PumlEntityFkList docs.RepoObject_PlantUml_FkRefList <.. docs.RepoObject_Plantuml docs.RepoObject_PlantUml_PumlEntityFkList <.. docs.RepoObject_Plantuml docs.RepoObject_Plantuml_T <.. docs.usp_PERSIST_RepoObject_Plantuml_T docs.RepoObject_Plantuml_T <.. docs.RepoObject_Adoc docs.Schema_EntityList <.. docs.Schema_puml docs.Schema_puml <.. docs.AntoraNavListPage_by_schema docs.Schema_PumlPartial_FkRefList <.. docs.Schema_puml docs.usp_AntoraExport_ObjectPartialsContent <.. docs.usp_AntoraExport docs.usp_AntoraExport_ObjectPuml <.. docs.usp_AntoraExport docs.usp_PERSIST_RepoObject_Adoc_T <.. docs.usp_AntoraExport_ObjectPartialsContent docs.usp_PERSIST_RepoObject_IndexList_T <.. docs.usp_AntoraExport_ObjectPartialsContent docs.usp_PERSIST_RepoObject_Plantuml_Entity_T <.. docs.usp_AntoraExport_ObjectPuml docs.usp_PERSIST_RepoObject_Plantuml_T <.. docs.usp_AntoraExport_ObjectPuml repo.ForeignKey_gross <.. docs.RepoObject_IndexList repo.ForeignKey_Indexes <.. repo.usp_Index_ForeignKey repo.ForeignKey_Indexes <.. repo.ForeignKey_Indexes_union repo.ForeignKey_Indexes_union <.. repo.ForeignKey_Indexes_union_T repo.ForeignKey_Indexes_union <.. repo.usp_PERSIST_ForeignKey_Indexes_union_T repo.ForeignKey_Indexes_union_T <.. docs.Schema_PumlPartial_FkRefList repo.ForeignKey_Indexes_union_T <.. docs.RepoObject_PlantUml_FkRefList repo.ForeignKey_Indexes_union_T <.. repo.usp_PERSIST_ForeignKey_Indexes_union_T repo.ForeignKey_Indexes_union_T <.. repo.usp_Index_finish repo.ForeignKey_Indexes_union_T <.. docs.ForeignKey_RelationScript repo.ForeignKey_Indexes_union_T <.. repo.ForeignKey_gross repo.ForeignKey_Indexes_union_T <.. repo.RepoObject_related_FK_union repo.ForeignKey_virtual_Indexes <.. repo.ForeignKey_Indexes_union repo.Index_ColumList <.. repo.Index_ColumList_T repo.Index_ColumList <.. repo.usp_PERSIST_Index_ColumList_T repo.Index_ColumList_T <.. repo.Index_SqlConstraint_PkUq repo.Index_ColumList_T <.. repo.usp_PERSIST_Index_ColumList_T repo.Index_ColumList_T <.. uspgenerator.GeneratorUspStep_Persistence_src repo.Index_ColumList_T <.. repo.Index_gross repo.Index_gross <.. repo.RepoObject_SqlCreateTable repo.Index_gross <.. repo.usp_index_inheritance repo.Index_gross <.. repo.usp_Index_virtual_set repo.Index_gross <.. repo.ForeignKey_Indexes repo.Index_gross <.. repo.ForeignKey_virtual_Indexes repo.Index_gross <.. repo.usp_Index_finish repo.Index_gross <.. docs.RepoObject_IndexList repo.Index_gross <.. docs.IndexSemanticgroupPatterndatatype repo.Index_gross <.. repo.ForeignKey_gross repo.Index_SqlConstraint_PkUq <.. repo.RepoObject_SqlCreateTable repo.RepoObject_related_FK_union <.. docs.RepoObject_PlantUml_PumlEntityFkList repo.RepoObject_related_FK_union <.. docs.RepoObject_PlantUml_FkRefList repo.RepoObject_SqlCreateTable <.. reference.ftv_RepoObject_ColumReferenceRepoObject repo.usp_Index_finish <.. repo.usp_index_inheritance repo.usp_Index_finish <.. repo.usp_Index_ForeignKey repo.usp_Index_ForeignKey <.. repo.usp_main repo.usp_index_inheritance <.. repo.usp_main repo.usp_Index_virtual_set <.. repo.usp_Index_ForeignKey repo.usp_PERSIST_ForeignKey_Indexes_union_T <.. repo.usp_Index_ForeignKey repo.usp_PERSIST_Index_ColumList_T <.. repo.usp_Index_finish uspgenerator.GeneratorUspStep_Persistence_src <.. uspgenerator.usp_GeneratorUsp_insert_update_persistence uspgenerator.usp_GeneratorUsp_insert_update_persistence <.. repo.usp_main footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_0_30_objectref[] === PlantUML 1 1 ColumnRef // tag::puml_entity_1_1_colref[] [plantuml, entity_1_1_colref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:repo.index_columlist.adoc[]"" as repo.Index_ColumList << V >> { AntoraIndexColumnList : (nvarchar(max)) ColumnList : (nvarchar(max)) ConstraintColumnList : (nvarchar(max)) DbmlIndexColumnList : (nvarchar(max)) - index_guid : (uniqueidentifier) PersistenceWhereColumnList : (nvarchar(max)) PumlIndexColumnList : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:repo.index_columlist_t.adoc[]"" as repo.Index_ColumList_T << U >> { - **index_guid** : (uniqueidentifier) AntoraIndexColumnList : (nvarchar(max)) ColumnList : (nvarchar(max)) ConstraintColumnList : (nvarchar(max)) DbmlIndexColumnList : (nvarchar(max)) PersistenceWhereColumnList : (nvarchar(max)) PumlIndexColumnList : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:repo.indexcolumn_union_t.adoc[]"" as repo.IndexColumn_union_T << U >> { **index_guid** : (uniqueidentifier) - **index_column_id** : (int) ColumnsPerIndex : (int) index_name : (nvarchar(450)) is_descending_key : (bit) is_index_primary_key : (bit) is_index_real : (bit) is_index_unique : (bit) parent_RepoObject_guid : (uniqueidentifier) parent_schema_name : (nvarchar(128)) parent_SysObject_fullname : (nvarchar(261)) parent_SysObject_name : (nvarchar(128)) RepoObjectColumn_guid : (uniqueidentifier) SysObject_column_name : (nvarchar(128)) SysObject_column_user_type_fullname : (nvarchar(182)) -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_index_columlist_t.adoc[]"" as repo.usp_PERSIST_Index_ColumList_T << P >> { -- } repo.Index_ColumList <.. repo.Index_ColumList_T repo.Index_ColumList <.. repo.usp_PERSIST_Index_ColumList_T repo.IndexColumn_union_T <.. repo.Index_ColumList ""repo.Index_ColumList::AntoraIndexColumnList"" <-- ""repo.Index_ColumList_T::AntoraIndexColumnList"" ""repo.Index_ColumList::ColumnList"" <-- ""repo.Index_ColumList_T::ColumnList"" ""repo.Index_ColumList::ConstraintColumnList"" <-- ""repo.Index_ColumList_T::ConstraintColumnList"" ""repo.Index_ColumList::DbmlIndexColumnList"" <-- ""repo.Index_ColumList_T::DbmlIndexColumnList"" ""repo.Index_ColumList::index_guid"" <-- ""repo.Index_ColumList_T::index_guid"" ""repo.Index_ColumList::PersistenceWhereColumnList"" <-- ""repo.Index_ColumList_T::PersistenceWhereColumnList"" ""repo.Index_ColumList::PumlIndexColumnList"" <-- ""repo.Index_ColumList_T::PumlIndexColumnList"" ""repo.IndexColumn_union_T::index_guid"" <-- ""repo.Index_ColumList::index_guid"" footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_colref[] == sql_modules_definition // tag::sql_modules_definition[] [%collapsible] ======= [source,sql,numbered,indent=0] ---- CREATE View [repo].[Index_ColumList] As Select col.index_guid , AntoraIndexColumnList = -- String_Agg ( Concat ( Cast(N'' As NVarchar(Max)) , '* <>; ' , col.SysObject_column_user_type_fullname ) , Char ( 13 ) + Char ( 10 ) ) Within Group(Order By col.index_column_id) --ColumnList doesn't contain Asc and Desc , ColumnList = -- String_Agg ( Concat ( --we need to convert to first argument nvarchar(max) to avoid the limit of 8000 byte Cast(' ' As NVarchar(Max)), QuoteName ( col.SysObject_column_name ) ) , ',' ) Within Group(Order By col.index_column_id) --ConstraintColumnList contains Asc and Desc , ConstraintColumnList = -- String_Agg ( Concat ( --we need to convert to first argument nvarchar(max) to avoid the limit of 8000 byte Cast(' ' As NVarchar(Max)) , QuoteName ( col.SysObject_column_name ) , Case col.is_descending_key When 1 Then ' DESC' Else ' ASC' End ) , ',' ) Within Group(Order By col.index_column_id) , DbmlIndexColumnList = -- String_Agg ( Concat ( --we need to convert to first argument nvarchar(max) to avoid the limit of 8000 byte Cast(' ' As NVarchar(Max)), QuoteName ( col.SysObject_column_name, '""' ) ) , ',' ) Within Group(Order By col.index_column_id) , PersistenceWhereColumnList = -- Stuff ( String_Agg ( Concat ( --we need to convert to first argument nvarchar(max) to avoid the limit of 8000 byte Cast('AND T.' As NVarchar(Max)) , QuoteName ( col.SysObject_column_name ) , ' = S.' , QuoteName ( col.SysObject_column_name ) , Char ( 13 ) , Char ( 10 ) ) , '' ) Within Group(Order By col.index_column_id) , 1 , 4 , Null ) , PumlIndexColumnList = -- String_Agg ( Concat ( Cast(N'' As NVarchar(Max)) , col.SysObject_column_name + '; ' , col.SysObject_column_user_type_fullname ) , Char ( 13 ) + Char ( 10 ) ) Within Group(Order By col.index_column_id) From repo.IndexColumn_union_T As col Group By col.index_guid ---- ======= // end::sql_modules_definition[] ",16225,True,3410.0272122762844,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, ANSI SQL parsing mode is enabled. */ public boolean ansi = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; singleInterval : INTERVAL? (intervalValue intervalUnit)+ EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER database db=errorCapturingIdentifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | ALTER database db=errorCapturingIdentifier SET locationSpec #setDatabaseLocation | DROP (database | NAMESPACE) (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE multipartIdentifier RENAME COLUMN from=qualifiedName TO to=identifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=qualifiedNameList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=qualifiedNameList #dropTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE multipartIdentifier (ALTER | CHANGE) COLUMN? qualifiedName (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE tableIdentifier partitionSpec? CHANGE COLUMN? colName=errorCapturingIdentifier colType colPosition? #changeColumn | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER TABLE tableIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER VIEW tableIdentifier ADD (IF NOT EXISTS)? partitionSpec+ #addTablePartition | ALTER TABLE tableIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER TABLE tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER VIEW tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* #dropTablePartitions | ALTER TABLE multipartIdentifier SET locationSpec #setTableLocation | ALTER TABLE tableIdentifier partitionSpec SET locationSpec #setPartitionLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW tableIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? qualifiedName AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? qualifiedName #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=errorCapturingIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) tableIdentifier ((FROM | IN) db=errorCapturingIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (qualifiedName | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) database EXTENDED? db=errorCapturingIdentifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING qualifiedName ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assign (',' assign)* ; assign : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | IDENTIFIER '->' expression #lambda | '(' IDENTIFIER (',' IDENTIFIER)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : {ansi}? INTERVAL? intervalField+ | {!ansi}? INTERVAL intervalField* ; intervalField : value=intervalValue unit=intervalUnit (TO to=intervalUnit)? ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER qualifiedName ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=qualifiedName dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!ansi}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {ansi}? ansiNonReserved #unquotedIdentifier | {!ansi}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `spark.sql.ansi.enabled=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `spark.sql.ansi.enabled=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `spark.sql.ansi.enabled=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12082,False,2259.0809576207475,median "CLASS zcl_abapgit_object_clas DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_program CREATE PUBLIC . PUBLIC SECTION. INTERFACES zif_abapgit_object . ALIASES mo_files FOR zif_abapgit_object~mo_files . METHODS constructor IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_language TYPE spras . PROTECTED SECTION. DATA: mi_object_oriented_object_fct TYPE REF TO zif_abapgit_oo_object_fnc, mv_skip_testclass TYPE abap_bool, mv_classpool_name TYPE progname. METHODS: deserialize_abap IMPORTING ii_xml TYPE REF TO zif_abapgit_xml_input iv_package TYPE devclass RAISING zcx_abapgit_exception, deserialize_docu IMPORTING ii_xml TYPE REF TO zif_abapgit_xml_input RAISING zcx_abapgit_exception, deserialize_tpool IMPORTING ii_xml TYPE REF TO zif_abapgit_xml_input RAISING zcx_abapgit_exception, deserialize_sotr IMPORTING ii_ml TYPE REF TO zif_abapgit_xml_input iv_package TYPE devclass RAISING zcx_abapgit_exception, serialize_xml IMPORTING ii_xml TYPE REF TO zif_abapgit_xml_output RAISING zcx_abapgit_exception, serialize_attr IMPORTING !ii_xml TYPE REF TO zif_abapgit_xml_output !iv_clsname TYPE seoclsname RAISING zcx_abapgit_exception, serialize_descr IMPORTING !ii_xml TYPE REF TO zif_abapgit_xml_output !iv_clsname TYPE seoclsname RAISING zcx_abapgit_exception, serialize_docu IMPORTING !ii_xml TYPE REF TO zif_abapgit_xml_output !it_langu_additional TYPE zif_abapgit_lang_definitions=>ty_langus OPTIONAL !iv_clsname TYPE seoclsname RAISING zcx_abapgit_exception, serialize_tpool IMPORTING !ii_xml TYPE REF TO zif_abapgit_xml_output !it_langu_additional TYPE zif_abapgit_lang_definitions=>ty_langus OPTIONAL !iv_clsname TYPE seoclsname RAISING zcx_abapgit_exception, serialize_sotr IMPORTING !ii_xml TYPE REF TO zif_abapgit_xml_output RAISING zcx_abapgit_exception, source_apack_replacement CHANGING !ct_source TYPE seop_source_string RAISING zcx_abapgit_exception, repo_apack_replacement CHANGING !ct_source TYPE seop_source_string RAISING zcx_abapgit_exception. PRIVATE SECTION. METHODS: is_class_locked RETURNING VALUE(rv_is_class_locked) TYPE abap_bool RAISING zcx_abapgit_exception. METHODS interface_replacement IMPORTING !iv_from_interface TYPE seoclsname !iv_to_interface TYPE seoclsname CHANGING !ct_source TYPE seop_source_string . ENDCLASS. CLASS zcl_abapgit_object_clas IMPLEMENTATION. METHOD constructor. super->constructor( is_item = is_item iv_language = iv_language ). CREATE OBJECT mi_object_oriented_object_fct TYPE zcl_abapgit_oo_class. mv_classpool_name = cl_oo_classname_service=>get_classpool_name( |{ is_item-obj_name }| ). ENDMETHOD. METHOD deserialize_abap. DATA: ls_vseoclass TYPE vseoclass, lt_source TYPE seop_source_string, lt_local_definitions TYPE seop_source_string, lt_local_implementations TYPE seop_source_string, lt_local_macros TYPE seop_source_string, lt_test_classes TYPE seop_source_string, lt_descriptions TYPE zif_abapgit_oo_object_fnc=>ty_seocompotx_tt, ls_class_key TYPE seoclskey, lt_attributes TYPE zif_abapgit_definitions=>ty_obj_attribute_tt. lt_source = mo_files->read_abap( ). lt_local_definitions = mo_files->read_abap( iv_extra = zif_abapgit_oo_object_fnc=>c_parts-locals_def iv_error = abap_false ). lt_local_implementations = mo_files->read_abap( iv_extra = zif_abapgit_oo_object_fnc=>c_parts-locals_imp iv_error = abap_false ). lt_local_macros = mo_files->read_abap( iv_extra = zif_abapgit_oo_object_fnc=>c_parts-macros iv_error = abap_false ). lt_test_classes = mo_files->read_abap( iv_extra = zif_abapgit_oo_object_fnc=>c_parts-testclasses iv_error = abap_false ). ls_class_key-clsname = ms_item-obj_name. ii_xml->read( EXPORTING iv_name = 'VSEOCLASS' CHANGING cg_data = ls_vseoclass ). ii_xml->read( EXPORTING iv_name = 'ATTRIBUTES' CHANGING cg_data = lt_attributes ). "" Remove code for test classes if they have been deleted IF ls_vseoclass-with_unit_tests = abap_false. CLEAR lt_test_classes. ENDIF. mi_object_oriented_object_fct->create( EXPORTING iv_package = iv_package it_attributes = lt_attributes CHANGING cg_properties = ls_vseoclass ). mi_object_oriented_object_fct->generate_locals( is_key = ls_class_key it_local_definitions = lt_local_definitions it_local_implementations = lt_local_implementations it_local_macros = lt_local_macros it_local_test_classes = lt_test_classes ). repo_apack_replacement( CHANGING ct_source = lt_source ). mi_object_oriented_object_fct->deserialize_source( is_key = ls_class_key it_source = lt_source ). ii_xml->read( EXPORTING iv_name = 'DESCRIPTIONS' CHANGING cg_data = lt_descriptions ). mi_object_oriented_object_fct->update_descriptions( is_key = ls_class_key it_descriptions = lt_descriptions ). mi_object_oriented_object_fct->add_to_activation_list( ms_item ). ENDMETHOD. METHOD deserialize_docu. DATA: lt_lines TYPE tlinetab, lv_object TYPE dokhl-object, lt_i18n_lines TYPE zif_abapgit_lang_definitions=>ty_i18n_lines, ls_i18n_lines TYPE zif_abapgit_lang_definitions=>ty_i18n_line. ii_xml->read( EXPORTING iv_name = 'LINES' CHANGING cg_data = lt_lines ). lv_object = ms_item-obj_name. IF lines( lt_lines ) = 0. mi_object_oriented_object_fct->delete_documentation( iv_object_name = lv_object iv_language = mv_language ). RETURN. ENDIF. mi_object_oriented_object_fct->create_documentation( it_lines = lt_lines iv_object_name = lv_object iv_language = mv_language ). ii_xml->read( EXPORTING iv_name = 'I18N_LINES' CHANGING cg_data = lt_i18n_lines ). LOOP AT lt_i18n_lines INTO ls_i18n_lines. mi_object_oriented_object_fct->create_documentation( it_lines = ls_i18n_lines-lines iv_object_name = lv_object iv_language = ls_i18n_lines-language iv_no_masterlang = abap_true ). ENDLOOP. ENDMETHOD. METHOD deserialize_sotr. ""OTR stands for Online Text Repository mi_object_oriented_object_fct->create_sotr( iv_object_name = ms_item-obj_name iv_package = iv_package ii_xml = ii_ml ). ENDMETHOD. METHOD deserialize_tpool. DATA: lv_clsname TYPE seoclsname, lt_tpool_ext TYPE zif_abapgit_definitions=>ty_tpool_tt, lt_tpool TYPE textpool_table, lt_i18n_tpool TYPE zif_abapgit_lang_definitions=>ty_i18n_tpools, ls_i18n_tpool TYPE zif_abapgit_lang_definitions=>ty_i18n_tpool. ii_xml->read( EXPORTING iv_name = 'TPOOL' CHANGING cg_data = lt_tpool_ext ). lt_tpool = read_tpool( lt_tpool_ext ). IF lines( lt_tpool ) = 0. RETURN. ENDIF. lv_clsname = ms_item-obj_name. mi_object_oriented_object_fct->insert_text_pool( iv_class_name = lv_clsname it_text_pool = lt_tpool iv_language = mv_language ). ii_xml->read( EXPORTING iv_name = 'I18N_TPOOL' CHANGING cg_data = lt_i18n_tpool ). LOOP AT lt_i18n_tpool INTO ls_i18n_tpool. lt_tpool = read_tpool( ls_i18n_tpool-textpool ). mi_object_oriented_object_fct->insert_text_pool( iv_class_name = lv_clsname it_text_pool = lt_tpool iv_language = ls_i18n_tpool-language iv_state = 'A' ). ENDLOOP. ENDMETHOD. METHOD interface_replacement. DATA lv_tabix TYPE sy-tabix. FIELD-SYMBOLS LIKE LINE OF ct_source. FIND REGEX '^\\s*INTERFACES(:| )\\s*' && iv_from_interface && '\\s*.' IN TABLE ct_source MATCH LINE lv_tabix. IF sy-subrc = 0. READ TABLE ct_source ASSIGNING INDEX lv_tabix. ASSERT sy-subrc = 0. REPLACE FIRST OCCURRENCE OF iv_from_interface IN WITH iv_to_interface IGNORING CASE. REPLACE ALL OCCURRENCES OF iv_from_interface && '~descriptor' IN TABLE ct_source WITH iv_to_interface && '~descriptor' IGNORING CASE. REPLACE ALL OCCURRENCES OF iv_from_interface && '=>' IN TABLE ct_source WITH iv_to_interface && '=>' IGNORING CASE. REPLACE ALL OCCURRENCES OF iv_from_interface && '->' IN TABLE ct_source WITH iv_to_interface && '->' IGNORING CASE. ENDIF. ENDMETHOD. METHOD is_class_locked. DATA: lv_argument TYPE seqg3-garg. lv_argument = ms_item-obj_name. OVERLAY lv_argument WITH '=============================='. lv_argument = lv_argument && '*'. rv_is_class_locked = exists_a_lock_entry_for( iv_lock_object = 'ESEOCLASS' iv_argument = lv_argument ). ENDMETHOD. METHOD repo_apack_replacement. DATA lv_apack TYPE seoclsname. "" Check if SAP-version of APACK manifest exists SELECT SINGLE clsname INTO lv_apack FROM seoclass WHERE clsname = zif_abapgit_apack_definitions=>c_apack_interface_sap. IF sy-subrc = 0. RETURN. ENDIF. "" If not, replace with abapGit version interface_replacement( EXPORTING iv_from_interface = to_lower( zif_abapgit_apack_definitions=>c_apack_interface_sap ) iv_to_interface = to_lower( zif_abapgit_apack_definitions=>c_apack_interface_cust ) CHANGING ct_source = ct_source ). ENDMETHOD. METHOD serialize_attr. DATA: lt_attributes TYPE zif_abapgit_definitions=>ty_obj_attribute_tt. lt_attributes = mi_object_oriented_object_fct->read_attributes( iv_clsname ). IF lines( lt_attributes ) = 0. RETURN. ENDIF. ii_xml->add( iv_name = 'ATTRIBUTES' ig_data = lt_attributes ). ENDMETHOD. METHOD serialize_descr. DATA: lt_descriptions TYPE zif_abapgit_oo_object_fnc=>ty_seocompotx_tt, lv_language TYPE spras. IF ii_xml->i18n_params( )-main_language_only = abap_true. lv_language = mv_language. ENDIF. lt_descriptions = mi_object_oriented_object_fct->read_descriptions( iv_obejct_name = iv_clsname iv_language = lv_language ). IF lines( lt_descriptions ) = 0. RETURN. ENDIF. ii_xml->add( iv_name = 'DESCRIPTIONS' ig_data = lt_descriptions ). ENDMETHOD. METHOD serialize_docu. DATA: lt_lines TYPE tlinetab, lv_langu TYPE sy-langu, lt_i18n_lines TYPE zif_abapgit_lang_definitions=>ty_i18n_lines, ls_i18n_lines TYPE zif_abapgit_lang_definitions=>ty_i18n_line. lt_lines = mi_object_oriented_object_fct->read_documentation( iv_class_name = iv_clsname iv_language = mv_language ). IF lines( lt_lines ) > 0. ii_xml->add( iv_name = 'LINES' ig_data = lt_lines ). ENDIF. IF ii_xml->i18n_params( )-main_language_only = abap_true. RETURN. ENDIF. LOOP AT it_langu_additional INTO lv_langu. lt_lines = mi_object_oriented_object_fct->read_documentation( iv_class_name = iv_clsname iv_language = lv_langu ). IF lines( lt_lines ) > 0. CLEAR ls_i18n_lines. ls_i18n_lines-language = lv_langu. ls_i18n_lines-lines = lt_lines. INSERT ls_i18n_lines INTO TABLE lt_i18n_lines. ENDIF. ENDLOOP. IF lines( lt_i18n_lines ) > 0. ii_xml->add( iv_name = 'I18N_LINES' ig_data = lt_i18n_lines ). ENDIF. ENDMETHOD. METHOD serialize_sotr. mi_object_oriented_object_fct->read_sotr( iv_object_name = ms_item-obj_name ii_xml = ii_xml ). ENDMETHOD. METHOD serialize_tpool. DATA: lt_tpool TYPE textpool_table, lv_index TYPE i, lv_langu TYPE sy-langu, lt_i18n_tpool TYPE zif_abapgit_lang_definitions=>ty_i18n_tpools, ls_i18n_tpool TYPE zif_abapgit_lang_definitions=>ty_i18n_tpool. FIELD-SYMBOLS LIKE LINE OF lt_tpool. DATA lt_tpool_main LIKE SORTED TABLE OF WITH UNIQUE KEY id key. lt_tpool = mi_object_oriented_object_fct->read_text_pool( iv_class_name = iv_clsname iv_language = mv_language ). ii_xml->add( iv_name = 'TPOOL' ig_data = add_tpool( lt_tpool ) ). IF ii_xml->i18n_params( )-main_language_only = abap_true OR lines( lt_tpool ) = 0. RETURN. ENDIF. lt_tpool_main = lt_tpool. LOOP AT it_langu_additional INTO lv_langu. lt_tpool = mi_object_oriented_object_fct->read_text_pool( iv_class_name = iv_clsname iv_language = lv_langu ). LOOP AT lt_tpool ASSIGNING . lv_index = sy-tabix. READ TABLE lt_tpool_main WITH KEY id = -id key = -key TRANSPORTING NO FIELDS. IF sy-subrc <> 0. DELETE lt_tpool INDEX lv_index. ENDIF. ENDLOOP. IF lines( lt_tpool ) > 0. CLEAR ls_i18n_tpool. ls_i18n_tpool-language = lv_langu. ls_i18n_tpool-textpool = add_tpool( lt_tpool ). INSERT ls_i18n_tpool INTO TABLE lt_i18n_tpool. ENDIF. ENDLOOP. IF lines( lt_i18n_tpool ) > 0. ii_xml->add( iv_name = 'I18N_TPOOL' ig_data = lt_i18n_tpool ). ENDIF. ENDMETHOD. METHOD serialize_xml. DATA: ls_vseoclass TYPE vseoclass, ls_clskey TYPE seoclskey, lt_langu_additional TYPE zif_abapgit_lang_definitions=>ty_langus. ls_clskey-clsname = ms_item-obj_name. ""If class was deserialized with a previous versions of abapGit and current language was different ""from main language at this time, this call would return SY-LANGU as main language. To fix ""these objects, set SY-LANGU to main language temporarily. zcl_abapgit_language=>set_current_language( mv_language ). TRY. ls_vseoclass = mi_object_oriented_object_fct->get_class_properties( ls_clskey ). CLEANUP. zcl_abapgit_language=>restore_login_language( ). ENDTRY. zcl_abapgit_language=>restore_login_language( ). CLEAR: ls_vseoclass-uuid, ls_vseoclass-author, ls_vseoclass-createdon, ls_vseoclass-changedby, ls_vseoclass-changedon, ls_vseoclass-r3release, ls_vseoclass-chgdanyby, ls_vseoclass-chgdanyon, ls_vseoclass-clsfinal, ls_vseoclass-clsabstrct, ls_vseoclass-exposure, ls_vseoclass-version. IF mv_skip_testclass = abap_true. CLEAR ls_vseoclass-with_unit_tests. ENDIF. "" Table d010tinf stores info. on languages in which program is maintained "" Select all active translations of program texts "" Skip main language - it was already serialized SELECT DISTINCT language INTO TABLE lt_langu_additional FROM d010tinf WHERE r3state = 'A' AND prog = mv_classpool_name AND language <> mv_language. ii_xml->add( iv_name = 'VSEOCLASS' ig_data = ls_vseoclass ). serialize_tpool( ii_xml = ii_xml iv_clsname = ls_clskey-clsname it_langu_additional = lt_langu_additional ). IF ls_vseoclass-category = seoc_category_exception. serialize_sotr( ii_xml ). ENDIF. serialize_docu( ii_xml = ii_xml iv_clsname = ls_clskey-clsname it_langu_additional = lt_langu_additional ). serialize_descr( ii_xml = ii_xml iv_clsname = ls_clskey-clsname ). serialize_attr( ii_xml = ii_xml iv_clsname = ls_clskey-clsname ). ENDMETHOD. METHOD source_apack_replacement. DATA lv_clsname TYPE seoclsname. "" Check if abapGit version of APACK manifest is used SELECT SINGLE clsname INTO lv_clsname FROM seometarel WHERE clsname = ms_item-obj_name AND refclsname = zif_abapgit_apack_definitions=>c_apack_interface_cust AND version = '1'. IF sy-subrc <> 0. RETURN. ENDIF. "" If yes, replace with SAP-version interface_replacement( EXPORTING iv_from_interface = to_lower( zif_abapgit_apack_definitions=>c_apack_interface_cust ) iv_to_interface = to_lower( zif_abapgit_apack_definitions=>c_apack_interface_sap ) CHANGING ct_source = ct_source ). ENDMETHOD. METHOD zif_abapgit_object~changed_by. TYPES: BEGIN OF ty_includes, programm TYPE programm, END OF ty_includes. TYPES: BEGIN OF ty_reposrc, unam TYPE reposrc-unam, udat TYPE reposrc-udat, utime TYPE reposrc-utime, END OF ty_reposrc. DATA: lt_reposrc TYPE STANDARD TABLE OF ty_reposrc, ls_reposrc LIKE LINE OF lt_reposrc, lt_includes TYPE STANDARD TABLE OF ty_includes. lt_includes = mi_object_oriented_object_fct->get_includes( ms_item-obj_name ). ASSERT lines( lt_includes ) > 0. SELECT unam udat utime FROM reposrc INTO TABLE lt_reposrc FOR ALL ENTRIES IN lt_includes WHERE progname = lt_includes-programm AND r3state = 'A'. IF sy-subrc <> 0. rv_user = c_user_unknown. ELSE. SORT lt_reposrc BY udat DESCENDING utime DESCENDING. READ TABLE lt_reposrc INDEX 1 INTO ls_reposrc. ASSERT sy-subrc = 0. rv_user = ls_reposrc-unam. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: ls_clskey TYPE seoclskey. ls_clskey-clsname = ms_item-obj_name. mi_object_oriented_object_fct->delete( ls_clskey ). ENDMETHOD. METHOD zif_abapgit_object~deserialize. deserialize_abap( ii_xml = io_xml iv_package = iv_package ). deserialize_tpool( io_xml ). deserialize_sotr( ii_ml = io_xml iv_package = iv_package ). deserialize_docu( io_xml ). ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: ls_class_key TYPE seoclskey. ls_class_key-clsname = ms_item-obj_name. rv_bool = mi_object_oriented_object_fct->exists( ls_class_key ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. RETURN. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-abap TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. IF is_class_locked( ) = abap_true OR is_text_locked( mv_classpool_name ) = abap_true. rv_is_locked = abap_true. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~jump. "" Covered by ZCL_ABAPGIT_OBJECTS=>JUMP ENDMETHOD. METHOD zif_abapgit_object~serialize. DATA: lt_source TYPE seop_source_string, ls_class_key TYPE seoclskey. ls_class_key-clsname = ms_item-obj_name. IF zif_abapgit_object~exists( ) = abap_false. RETURN. ENDIF. CALL FUNCTION 'SEO_BUFFER_REFRESH' EXPORTING version = seoc_version_active force = abap_true. CALL FUNCTION 'SEO_BUFFER_REFRESH' EXPORTING version = seoc_version_inactive force = abap_true. lt_source = mi_object_oriented_object_fct->serialize_abap( ls_class_key ). source_apack_replacement( CHANGING ct_source = lt_source ). mo_files->add_abap( lt_source ). lt_source = mi_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_locals_def ). IF lines( lt_source ) > 0. mo_files->add_abap( iv_extra = zif_abapgit_oo_object_fnc=>c_parts-locals_def it_abap = lt_source ). ENDIF. lt_source = mi_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_locals_imp ). IF lines( lt_source ) > 0. mo_files->add_abap( iv_extra = zif_abapgit_oo_object_fnc=>c_parts-locals_imp it_abap = lt_source ). ENDIF. lt_source = mi_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_testclasses ). mv_skip_testclass = mi_object_oriented_object_fct->get_skip_test_classes( ). IF lines( lt_source ) > 0 AND mv_skip_testclass = abap_false. mo_files->add_abap( iv_extra = zif_abapgit_oo_object_fnc=>c_parts-testclasses it_abap = lt_source ). ENDIF. lt_source = mi_object_oriented_object_fct->serialize_abap( is_class_key = ls_class_key iv_type = seop_ext_class_macros ). IF lines( lt_source ) > 0. mo_files->add_abap( iv_extra = zif_abapgit_oo_object_fnc=>c_parts-macros it_abap = lt_source ). ENDIF. serialize_xml( io_xml ). ENDMETHOD. ENDCLASS. ",5821,False,1277.1174004013894,median "ifdef::env-github[] NOTE: Release notes are best read in our documentation at https://www.elastic.co/guide/en/apm/agent/java/current/release-notes.html[elastic.co] endif::[] //// [[release-notes-x.x.x]] ==== x.x.x - YYYY/MM/DD [float] ===== Breaking changes [float] ===== Features * Cool new feature: {pull}2526[#2526] [float] ===== Bug fixes //// === Unreleased [[release-notes-1.23.1]] ==== 1.23.1 - YYYY/MM/DD [float] ===== Features * Basic support for Apache Struts 2 {pull}1763[#1763] * Extending the <> config option to enable the overriding of logs with ECS-reformatted events. With the new `OVERRIDE` option, non-file logs can be ECS-reformatted automatically as well - {pull}1793[#1793] * Instrumentation for Vert.x Web {pull}1697[#1697] * Changed log level of vm arguments to debug [float] ===== Bug fixes * Fix another error related to instrumentation plugins loading on Windows - {pull}1785[#1785] * Load Spring AMQP plugin- {pull}1784[#1784] * Avoid `IllegalStateException` when multiple `tracestate` headers are used - {pull}1808[#1808] * Ensure CLI attach avoids `sudo` only when required and avoid blocking - {pull}1819[#1819] [float] ===== Refactors * Remove single-package limitation for embedded plugins - {pull}1780[#1780] [[release-notes-1.x]] === Java Agent version 1.x [[release-notes-1.23.0]] ==== 1.23.0 - 2021/04/22 [float] ===== Breaking changes * There are breaking changes in the <>. See the Features section for more information. [float] ===== Features * Overhaul of the <> application that allows to attach the agent to running JVMs - {pull}1667[#1667] ** The artifact of the standalone cli applicaiton is now called `apm-agent-attach-cli`. The attacher API is still called `apm-agent-attach`. ** There is also a slim version of the cli application that does not bundle the Java agent. It requires the `--agent-jar` option to be set. ** Improved logging + The application uses {ecs-logging-java-ref}/intro.html[Java ECS logging] to emit JSON logs. The log level can be configured with the `--log-level` option. By default, the program is logging to the console but using the `--log-file` option, it can also log to a file. ** Attach to JVMs running under a different user (unix only) + The JVM requires the attacher to be running under the same user as the target VM (the attachee). The `apm-agent-attach-standalone.jar` can now be run with a user that has permissions to switch to the user that runs the target VM. On Windows, the attacher can still only attach to JVMs that are running with under the same user. ** New include/exclude discovery rules + *** `--include-all`: Attach to all discovered JVMs. If no matchers are provided, it will not attach to any JVMs. *** `--include-user`/`--exclude-user`: Attach to all JVMs of a given operating system user. *** `--include-main`/`--exclude-main`: Attach to all JVMs that whose main class/jar name, or system properties match the provided regex. *** `--include-vmargs`/`--exclude-vmargs`: Attach to all JVMs that whose main class/jar name, or system properties match the provided regex. ** Removal of options + *** The deprecated `--arg` option has been removed. *** The `-i`/`--include`, `-e`/`exclude` options have been removed in favor of the `---` options. *** The `-p`/`--pid` options have been removed in favor of the `--include-pid` option. ** Changed behavior of the `-l`/`--list` option + The option now only lists JVMs that match the include/exclude discovery rules. Thus, it can be used to do a dry-run of the matchers without actually performing an attachment. It even works in combination with `--continuous` now. By default, the VM arguments are not printed, but only when the `-a`/`--list-vmargs` option is set. ** Remove dependency on `jps` + Even when matching on the main class name or on system properties, ** Checks the Java version before attaching to avoid attachment on unsupported JVMs. * Cassandra instrumentation - {pull}1712[#1712] * Log correlation supports JBoss Logging - {pull}1737[#1737] * Update Byte-buddy to `1.11.0` - {pull}1769[#1769] * Support for user.domain {pull}1756[#1756] * JAX-RS supports javax.ws.rs.PATCH * Enabling build and unit tests on Windows - {pull}1671[#1671] [float] ===== Bug fixes * Fixed log correlation for log4j2 - {pull}1720[#1720] * Fix apm-log4j1-plugin and apm-log4j2-plugin dependency on slf4j - {pull}1723[#1723] * Avoid systematic `MessageNotWriteableException` error logging, now only visible in `debug` - {pull}1715[#1715] and {pull}1730[#1730] * Fix rounded number format for non-english locales - {pull}1728[#1728] * Fix `NullPointerException` on legacy Apache client instrumentation when host is `null` - {pull}1746[#1746] * Apply consistent proxy class exclusion heuristic - {pull}1738[#1738] * Fix micrometer serialization error - {pull}1741[#1741] * Optimize & avoid `ensureInstrumented` deadlock by skipping stack-frame computation for Java7+ bytecode - {pull}1758[#1758] * Fix instrumentation plugins loading on Windows - {pull}1671[#1671] [float] ===== Refactors * Migrate some plugins to indy dispatcher {pull}1369[#1369] {pull}1410[#1410] {pull}1374[#1374] [[release-notes-1.22.0]] ==== 1.22.0 - 2021/03/24 [float] ===== Breaking changes * Dots in metric names of Micrometer metrics get replaced with underscores to avoid mapping conflicts. De-dotting be disabled via <>. - {pull}1700[#1700] [float] ===== Features * Introducing a new mechanism to ease the development of community instrumentation plugins. See <> for more details. This configuration was already added in 1.18.0, but more extensive and continuous integration testing allows us to expose it now. It is still marked as ""experimental"" though, meaning that future changes in the mechanism may break early contributed plugins. However, we highly encourage our community to try it out and we will do our best to assist with such efforts. * Deprecating `ignore_user_agents` in favour of `transaction_ignore_user_agents`, maintaining the same functionality - {pull}1644[#1644] * Update existing Hibernate Search 6 instrumentation to the final relase * The <> option is now dynamic * Flushing internal and micrometer metrics before the agent shuts down - {pull}1658[#1658] * Support for OkHttp 4.4+ - {pull}1672[#1672] * Adding capability to automatically create ECS-JSON-formatted version of the original application log files, through the <> config option. This allows effortless ingestion of logs to Elasticsearch without any further configuration. Supports log4j1, log4j2 and Logback. {pull}1261[#1261] * Add support to Spring AMQP - {pull}1657[#1657] * Adds the ability to automatically configure usage of the OpenTracing bridge in systems using ServiceLoader - {pull}1708[#1708] * Update to async-profiler 1.8.5 - includes a fix to a Java 7 crash and enhanced safe mode to better deal with corrupted stack frames. * Add a warning on startup when `-Xverify:none` or `-noverify` flags are set as this can lead to crashes that are very difficult to debug - {pull}1593[#1593]. In an upcoming version, the agent will not start when these flags are set, unless the system property `elastic.apm.disable_bootstrap_checks` is set to true. [float] ===== Bug fixes * fix sample rate rounded to zero when lower than precision - {pull}1655[#1655] * fixed a couple of bugs with the external plugin mechanism (not documented until now) - {pull}1660[#1660] * Fix runtime attach conflict with multiple users - {pull}1704[#1704] [[release-notes-1.21.0]] ==== 1.21.0 - 2021/02/09 [float] ===== Breaking changes * Following PR {pull}1650[#1650], there are two slight changes with the <> and <> configuration options: 1. So far, setting `server_urls` with an empty string would allow the agent to work normally, apart from any action that requires communication with the APM Server, including the attempt to fetch a central configuration. Starting in this agent version, setting `server_urls` to empty string doesn't have any special meaning, it is the default expected configuration, where `server_url` will be used instead. In order to achieve the same behaviour, use the new <> configuration. 2. Up to this version, `server_url` was used as an alias to `server_urls`, meaning that one could potentially set the `server_url` config with a comma-separated list of multiple APM Server addresses, and that would have been a valid configuration. Starting in this agent version, `server_url` is a separate configuration, and it only accepts Strings that represent a single valid URL. Specifically, empty strings and commas are invalid. [float] ===== Features * Add cloud provider metadata to reported events, see https://github.com/elastic/apm/blob/master/specs/agents/metadata.md#cloud-provider-metadata[spec] for details. By default, the agent will try to automatically detect the cloud provider on startup, but this can be configured through the <> config option - {pull}1599[#1599] * Add span & transaction `outcome` field to improve error rate calculations - {pull}1613[#1613] [float] ===== Bug fixes * Fixing crashes observed in Java 7 at sporadic timing by applying a few seconds delay on bootstrap - {pull}1594[#1594] * Fallback to using ""TLS"" `SSLContext` when ""SSL"" is not available - {pull}1633[#1633] * Fixing agent startup failure with `NullPointerException` thrown by Byte-buddy's `MultipleParentClassLoader` - {pull}1647[#1647] * Fix cached type resolution triggering `ClassCastException` - {pull}1649[#1649] [[release-notes-1.20.0]] ==== 1.20.0 - 2021/01/07 [float] ===== Breaking changes * The following public API types were `public` so far and became package-private: `NoopScope`, `ScopeImpl` and `AbstractSpanImpl`. If your code is using them, you will need to change that when upgrading to this version. Related PR: {pull}1532[#1532] [float] ===== Features * Add support for RabbitMQ clients - {pull}1328[#1328] [float] ===== Bug fixes * Fix small memory allocation regression introduced with tracestate header {pull}1508[#1508] * Fix `NullPointerException` from `WeakConcurrentMap.put` through the Elasticsearch client instrumentation - {pull}1531[#1531] * Sending `transaction_id` and `parent_id` only for events that contain a valid `trace_id` as well - {pull}1537[#1537] * Fix `ClassNotFoundError` with old versions of Spring resttemplate {pull}1524[#1524] * Fix Micrometer-driven metrics validation errors by the APM Server when sending with illegal values - {pull}1559[#1559] * Serialize all stack trace frames when setting `stack_trace_limit=-1` instead of none - {pull}1571[#1571] * Fix `UnsupportedOperationException` when calling `ServletContext.getClassLoader()` - {pull}1576[#1576] * Fix improper request body capturing - {pull}1579[#1579] * Avoid `NullPointerException` due to null return values instrumentation advices - {pull}1601[#1601] * Update async-profiler to 1.8.3 {pull}1602[1602] * Use null-safe data structures to avoid `NullPointerException` {pull}1597[1597] * Fix memory leak in sampling profiler mechanism - {pull}1592[#1592] [float] ===== Refactors * Migrate some plugins to indy dispatcher {pull}1405[#1405] {pull}1394[#1394] [[release-notes-1.19.0]] ==== 1.19.0 - 2020/11/10 [float] ===== Features * The agent version now includes a git hash if it's a snapshot version. This makes it easier to differ distinct snapshot builds of the same version. Example: `1.18.1-SNAPSHOT.4655910` * Add support for sampling weight with propagation in `tracestate` W3C header {pull}1384[#1384] * Adding two more valid options to the `log_level` config: `WARNING` (equivalent to `WARN`) and `CRITICAL` (will be treated as `ERROR`) - {pull}1431[1431] * Add the ability to disable Servlet-related spans for `INCLUDE`, `FORWARD` and `ERROR` dispatches (without affecting basic Servlet capturing) by adding `servlet-api-dispatch` to <> - {pull}1448[1448] * Add Sampling Profiler support for AArch64 architectures - {pull}1443[1443] * Support proper transaction naming when using Spring's `ServletWrappingController` - {pull}1461[#1461] * Update async-profiler to 1.8.2 {pull}1471[1471] * Update existing Hibernate Search 6 instrumentation to work with the latest CR1 release * Deprecating the `addLabel` public API in favor of `setLabel` (still supporting `addLabel`) - {pull}1449[#1449] [float] ===== Bug fixes * Fix `HttpUrlConnection` instrumentation issue (affecting distributed tracing as well) when using HTTPS without using `java.net.HttpURLConnection#disconnect` - {pull}1447[1447] * Fixes class loading issue that can occur when deploying multiple applications to the same application server - {pull}1458[#1458] * Fix ability to disable agent on startup wasn't working for runtime attach {pull}1444[1444] * Avoid `UnsupportedOperationException` on some spring application startup {pull}1464[1464] * Fix ignored runtime attach `config_file` {pull}1469[1469] * Fix `IllegalAccessError: Module 'java.base' no access to: package 'java.lang'...` in J9 VMs of Java version >= 9 - {pull}1468[#1468] * Fix JVM version parsing on HP-UX {pull}1477[#1477] * Fix Spring-JMS transactions lifecycle management when using multiple concurrent consumers - {pull}1496[#1496] [float] ===== Refactors * Migrate some plugins to indy dispatcher {pull}1404[1404] {pull}1411[1411] * Replace System Rules with System Lambda {pull}1434[#1434] [[release-notes-1.18.1]] ==== 1.18.1 - 2020/10/06 [float] ===== Refactors * Migrate some plugins to indy dispatcher {pull}1362[1362] {pull}1366[1366] {pull}1363[1363] {pull}1383[1383] {pull}1368[1368] {pull}1364[1364] {pull}1365[1365] {pull}1367[1367] {pull}1371[1371] [float] ===== Bug fixes * Fix instrumentation error for HttpClient - {pull}1402[#1402] * Eliminate `unsupported class version error` messages related to loading the Java 11 HttpClient plugin in pre-Java-11 JVMs {pull}1397[1397] * Fix rejected metric events by APM Server with response code 400 due to data validation error - sanitizing Micrometer metricset tag keys - {pull}1413[1413] * Fix invalid micrometer metrics with non-numeric values {pull}1419[1419] * Fix `NoClassDefFoundError` with JDBC instrumentation plugin {pull}1409[1409] * Apply `disable_metrics` config to Micrometer metrics - {pull}1421[1421] * Remove cgroup `inactive_file.bytes` metric according to spec {pull}1422[1422] [[release-notes-1.18.0]] ==== 1.18.0 - 2020/09/08 [float] ===== Features * Deprecating `ignore_urls` config in favour of <> to align with other agents, while still allowing the old config name for backward compatibility - {pull}1315[#1315] * Enabling instrumentation of classes compiled with Java 1.4. This is reverting the restriction of instrumenting only bytecode of Java 1.5 or higher ({pull}320[#320]), which was added due to potential `VerifyError`. Such errors should be avoided now by the usage of `TypeConstantAdjustment` - {pull}1317[#1317] * Enabling agent to work without attempting any communication with APM server, by allowing setting `server_urls` with an empty string - {pull}1295[#1295] * Add <> - {pull}1303[#1303] * Add `profiling_inferred_spans_lib_directory` option to override the default temp directory used for exporting the async-profiler library. This is useful for server-hardened environments where `/tmp` is often configured with `noexec`, leading to `java.lang.UnsatisfiedLinkError` errors - {pull}1350[#1350] * Create spans for Servlet dispatches to FORWARD, INCLUDE and ERROR - {pull}1212[#1212] * Support JDK 11 HTTPClient - {pull}1307[#1307] * Lazily create profiler temporary files {pull}1360[#1360] * Convert the followings to Indy Plugins (see details in <>): gRPC, AsyncHttpClient, Apache HttpClient * The agent now collects cgroup memory metrics (see details in <>) * Update async-profiler to 1.8.1 {pull}1382[#1382] * Runtime attach install option is promoted to 'beta' status (was experimental). [float] ===== Bug fixes * Fixes a `NoClassDefFoundError` in the JMS instrumentation of `MessageListener` - {pull}1287[#1287] * Fix `/ by zero` error message when setting `server_urls` with an empty string - {pull}1295[#1295] * Fix `ClassNotFoundException` or `ClassCastException` in some cases where special log4j configurations are used - {pull}1322[#1322] * Fix `NumberFormatException` when using early access Java version - {pull}1325[#1325] * Fix `service_name` config being ignored when set to the same auto-discovered default value - {pull}1324[#1324] * Fix service name error when updating a web app on a Servlet container - {pull}1326[#1326] * Fix remote attach 'jps' executable not found when 'java' binary is symlinked ot a JRE - {pull}1352[#1352] [[release-notes-1.18.0.rc1]] ==== 1.18.0.RC1 - 2020/07/22 This release candidate adds some highly anticipated features: It’s now possible to attach the agent at runtime in more cases than before. Most notably, it enables runtime attachment on JBoss, WildFly, Glassfish/Payara, and other OSGi runtimes such as Atlassian Jira and Confluence. To make this and other significant features, such as https://github.com/elastic/apm-agent-java/issues/937[external plugins], possible, we have implemented major changes to the architecture of the agent. The agent now relies on the `invokedynamic` bytecode instruction to make plugin development easier, safer, and more efficient. As early versions of Java 7 and Java 8 have unreliable support for invokedynamic, we now require a minimum update level of 60 for Java 7 (7u60+) in addition to the existing minimum update level of 40 for Java 8 (8u40+). We’re looking for users who would like to try this out to give feedback. If we see that the `invokedynamic`-based approach (https://github.com/elastic/apm-agent-java/pull/1230[indy plugins]) works well, we can continue and migrate the rest of the plugins. After the migration has completed, we can move forward with external plugins and remove the experimental label from runtime attachment. If all works like in our testing, you would not see `NoClassDefFoundError` s anymore when, for example, trying to attach the agent at runtime to an OSGi container or a JBoss server. Also, non-standard OSGi containers, such as Atlassian Jira and other technologies with restrictive class loading policies, such as MuleSoft ESB, will benefit from this change. In the worst case, there might be JVM crashes due to `invokedynamic`-related JVM bugs. However, we already disable the agent when attached to JVM versions that are known to be problematic. Another potentially problematic area is that we now dynamically raise the bytecode version of instrumented classes to be at least bytecode version 51 (Java 7). This is needed in order to be able to use the `invokedynamic` instruction. This requires re-computation of stack map frames which makes instrumentation a bit slower. We don't anticipate notable slowdowns unless you extensively (over-)use <>. [float] ===== Breaking changes * Early Java 7 versions, prior to update 60, are not supported anymore. When trying to attach to a non-supported version, the agent will disable itself and not apply any instrumentations. [float] ===== Features * Experimental support for runtime attachment now also for OSGi containers, JBoss, and WildFly * New mitigation of OSGi bootdelegation errors (`NoClassDefFoundError`). You can remove any `org.osgi.framework.bootdelegation` related configuration. This release also removes the configuration option `boot_delegation_packages`. * Overhaul of the `ExecutorService` instrumentation that avoids `ClassCastException` issues - {pull}1206[#1206] * Support for `ForkJoinPool` and `ScheduledExecutorService` (see <>) * Support for `ExecutorService#invokeAny` and `ExecutorService#invokeAll` * Added support for `java.util.TimerTask` - {pull}1235[#1235] * Add capturing of request body in Elasticsearch queries: `_msearch`, `_count`, `_msearch/template`, `_search/template`, `_rollup_search` - {pull}1222[#1222] * Add <> flag * Add experimental support for Scala Futures * The agent now collects heap memory pools metrics - {pull}1228[#1228] [float] ===== Bug fixes * Fixes error capturing for log4j2 loggers. Version 1.17.0 introduced a regression. * Fixes `NullPointerException` related to JAX-RS and Quartz instrumentation - {pull}1249[#1249] * Expanding k8s pod ID discovery to some formerly non-supported environments * When `recording` is set to `false`, the agent will not send captured errors anymore. * Fixes NPE in Dubbo instrumentation that occurs when the application is acting both as a provider and as a consumer - {pull}1260[#1260] * Adding a delay by default what attaching the agent to Tomcat using the premain route to work around the JUL deadlock issue - {pull}1262[#1262] * Fixes missing `jboss.as:*` MBeans on JBoss - {pull}1257[#1257] [[release-notes-1.17.0]] ==== 1.17.0 - 2020/06/17 [float] ===== Features * Log files are now rotated after they reach <>. There will always be one history file `${log_file}.1`. * Add <> and <> with the options `PLAIN_TEXT` and `JSON`. The latter uses https://github.com/elastic/ecs-logging-java[ecs-logging-java] to format the logs. * Exposing <> config - {pull}1187[#1187] * Add support for naming transactions based on Grails controllers. Supports Grails 3+ - {pull}1171[#1171] * Add support for the Apache/Alibaba Dubbo RPC framework * Async Profiler version upgraded to 1.7.1, with a new debugging flag for the stack frame recovery mechanism - {pull}1173[#1173] [float] ===== Bug fixes * Fixes `IndexOutOfBoundsException` that can occur when profiler-inferred spans are enabled. This also makes the profiler more resilient by just removing the call tree related to the exception (which might be in an invalid state) as opposed to stopping the profiler when an exception occurs. * Fix `NumberFormatException` when parsing Ingres/Actian JDBC connection strings - {pull}1198[#1198] * Prevent agent from overriding JVM configured truststore when not using HTTPS for communication with APM server - {pull}1203[#1203] * Fix `java.lang.IllegalStateException` with `jps` JVM when using continuous runtime attach - {pull}1205[1205] * Fix agent trying to load log4j2 plugins from application - {pull}1214[1214] * Fix memory leak in gRPC instrumentation plugin - {pull}1196[1196] * Fix HTTPS connection failures when agent is configured to use HTTPS to communicate with APM server {pull}1209[1209] [[release-notes-1.16.0]] ==== 1.16.0 - 2020/05/13 [float] ===== Features * The log correlation feature now adds `error.id` to the MDC. See <> for details. - {pull}1050[#1050] * Deprecating the `incubating` tag in favour of the `experimental` tag. This is not a breaking change, so former <> configuration containing the `incubating` tag will still be respected - {pull}1123[#1123] * Add a `--without-emulated-attach` option for runtime attachment to allow disabling this feature as a workaround. * Add workaround for JDK bug JDK-8236039 with TLS 1.3 {pull}1149[#1149] * Add log level `OFF` to silence agent logging * Adds <> option to exclude fast executing spans. When set together with one of the more specific thresholds - `trace_methods_duration_threshold` or `profiling_inferred_spans_min_duration`, the higher threshold will determine which spans will be discarded. * Automatically instrument quartz jobs from the quartz-jobs artifact {pull}1170[#1170] * Perform re-parenting of regular spans to be a child of profiler-inferred spans. Requires APM Server and Kibana 7.8.0. {pull}1117[#1117] * Upgrade Async Profiler version to 1.7.0 [float] ===== Bug fixes * When Servlet-related Exceptions are handled through exception handlers that return a 200 status code, agent shouldn't override with 500 - {pull}1103[#1103] * Exclude Quartz 1 from instrumentation to avoid `IncompatibleClassChangeError: Found class org.quartz.JobExecutionContext, but interface was expected` - {pull}1108[#1108] * Fix breakdown metrics span sub-types {pull}1113[#1113] * Fix flaky gRPC server instrumentation {pull}1122[#1122] * Fix side effect of calling `Statement.getUpdateCount` more than once {pull}1139[#1139] * Stop capturing JDBC affected rows count using `Statement.getUpdateCount` to prevent unreliable side-effects {pull}1147[#1147] * Fix OpenTracing error tag handling (set transaction error result when tag value is `true`) {pull}1159[#1159] * Due to a bug in the build we didn't include the gRPC plugin in the build so far * `java.lang.ClassNotFoundException: Unable to load class 'jdk.internal...'` is thrown when tracing specific versions of Atlassian systems {pull}1168[#1168] * Make sure spans are kept active during `AsyncHandler` methods in the `AsyncHttpClient` * CPU and memory metrics are sometimes not reported properly when using IBM J9 {pull}1148[#1148] * `NullPointerException` thrown by the agent on WebLogic {pull}1142[#1142] [[release-notes-1.15.0]] ==== 1.15.0 - 2020/03/27 [float] ===== Breaking changes * Ordering of configuration sources has slightly changed, please review <>: ** `elasticapm.properties` file now has higher priority over java system properties and environment variables, + This change allows to change dynamic options values at runtime by editing file, previously values set in java properties or environment variables could not be overridden, even if they were dynamic. * Renamed some configuration options related to the experimental profiler-inferred spans feature ({pull}1084[#1084]): ** `profiling_spans_enabled` -> `profiling_inferred_spans_enabled` ** `profiling_sampling_interval` -> `profiling_inferred_spans_sampling_interval` ** `profiling_spans_min_duration` -> `profiling_inferred_spans_min_duration` ** `profiling_included_classes` -> `profiling_inferred_spans_included_classes` ** `profiling_excluded_classes` -> `profiling_inferred_spans_excluded_classes` ** Removed `profiling_interval` and `profiling_duration` (both are fixed to 5s now) [float] ===== Features * Gracefully abort agent init when running on a known Java 8 buggy JVM {pull}1075[#1075]. * Add support for <> * Makes <>, <>, and <> dynamic. Note that changing these values at runtime can slow down the application temporarily. * Do not instrument Servlet API before 3.0 {pull}1077[#1077] * Add support for API keys for apm backend authentication {pull}1083[#1083] * Add support for <> client & server instrumentation {pull}1019[#1019] * Deprecating `active` configuration option in favor of `recording`. Setting `active` still works as it's now an alias for `recording`. [float] ===== Bug fixes * When JAX-RS-annotated method delegates to another JAX-RS-annotated method, transaction name should include method A - {pull}1062[#1062] * Fixed bug that prevented an APM Error from being created when calling `org.slf4j.Logger#error` - {pull}1049[#1049] * Wrong address in JDBC spans for Oracle, MySQL and MariaDB when multiple hosts are configured - {pull}1082[#1082] * Document and re-order configuration priorities {pull}1087[#1087] * Improve heuristic for `service_name` when not set through config {pull}1097[#1097] [[release-notes-1.14.0]] ==== 1.14.0 - 2020/03/04 [float] ===== Features * Support for the official https://www.w3.org/TR/trace-context[W3C] `traceparent` and `tracestate` headers. + The agent now accepts both the `elastic-apm-traceparent` and the official `traceparent` header. By default, it sends both headers on outgoing requests, unless <> is set to false. * Creating spans for slow methods with the help of the sampling profiler https://github.com/jvm-profiling-tools/async-profiler[async-profiler]. This is a low-overhead way of seeing which methods make your transactions slow and a replacement for the `trace_methods` configuration option. See <> for more details * Adding a Circuit Breaker to pause the agent when stress is detected on the system and resume when the stress is relieved. See <> and {pull}1040[#1040] for more info. * `Span#captureException` and `Transaction#captureException` in public API return reported error id - {pull}1015[#1015] [float] ===== Bug fixes * java.lang.IllegalStateException: Cannot resolve type description for - {pull}1037[#1037] * properly handle `java.sql.SQLException` for unsupported JDBC features {pull}[#1035] https://github.com/elastic/apm-agent-java/issues/1025[#1025] [[release-notes-1.13.0]] ==== 1.13.0 - 2020/02/11 [float] ===== Features * Add support for <> * Add `context.message.age.ms` field for JMS message receiving spans and transactions - {pull}970[#970] * Instrument log4j2 Logger#error(String, Throwable) ({pull}919[#919]) Automatically captures exceptions when calling `logger.error(""message"", exception)` * Add instrumentation for external process execution through `java.lang.Process` and Apache `commons-exec` - {pull}903[#903] * Add `destination` fields to exit span contexts - {pull}976[#976] * Removed `context.message.topic.name` field - {pull}993[#993] * Add support for Kafka clients - {pull}981[#981] * Add support for binary `traceparent` header format (see the https://github.com/elastic/apm/blob/master/docs/agent-development.md#Binary-Fields[spec] for more details) - {pull}1009[#1009] * Add support for log correlation for log4j and log4j2, even when not used in combination with slf4j. See <> for details. [float] ===== Bug Fixes * Fix parsing value of `trace_methods` configuration property {pull}930[#930] * Workaround for `java.util.logging` deadlock {pull}965[#965] * JMS should propagate traceparent header when transactions are not sampled {pull}999[#999] * Spans are not closed if JDBC implementation does not support `getUpdateCount` {pull}1008[#1008] [[release-notes-1.12.0]] ==== 1.12.0 - 2019/11/21 [float] ===== Features * JMS Enhancements {pull}911[#911]: ** Add special handling for temporary queues/topics ** Capture message bodies of text Messages *** Rely on the existing `ELASTIC_APM_CAPTURE_BODY` agent config option (off by default). *** Send as `context.message.body` *** Limit size to 10000 characters. If longer than this size, trim to 9999 and append with ellipsis ** Introduce the `ignore_message_queues` configuration to disable instrumentation (message tagging) for specific queues/topics as suggested in {pull}710[#710] ** Capture predefined message headers and all properties *** Rely on the existing `ELASTIC_APM_CAPTURE_HEADERS` agent config option. *** Send as `context.message.headers` *** Sanitize sensitive headers/properties based on the `sanitize_field_names` config option * Added support for the MongoDB sync driver. See https://www.elastic.co/guide/en/apm/agent/java/master/supported-technologies-details.html#supported-databases[supported data stores]. [float] ===== Bug Fixes * JDBC regression- `PreparedStatement#executeUpdate()` and `PreparedStatement#executeLargeUpdate()` are not traced {pull}918[#918] * When systemd cgroup driver is used, the discovered Kubernetes pod UID contains ""_"" instead of ""-"" {pull}920[#920] * DB2 jcc4 driver is not traced properly {pull}926[#926] [[release-notes-1.11.0]] ==== 1.11.0 - 2019/10/31 [float] ===== Features * Add the ability to configure a unique name for a JVM within a service through the https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-node-name[`service_node_name`] config option] * Add ability to ignore some exceptions to be reported as errors https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-ignore-exceptions[ignore_exceptions] * Applying new logic for JMS `javax.jms.MessageConsumer#receive` so that, instead of the transaction created for the polling method itself (ie from `receive` start to end), the agent will create a transaction attempting to capture the code executed during actual message handling. This logic is suitable for environments where polling APIs are invoked within dedicated polling threads. This polling transaction creation strategy can be reversed through a configuration option (`message_polling_transaction_strategy`) that is not exposed in the properties file by default. * Send IP obtained through `javax.servlet.ServletRequest#getRemoteAddr()` in `context.request.socket.remote_address` instead of parsing from headers {pull}889[#889] * Added `ElasticApmAttacher.attach(String propertiesLocation)` to specify a custom properties location * Logs message when `transaction_max_spans` has been exceeded {pull}849[#849] * Report the number of affected rows by a SQL statement (UPDATE,DELETE,INSERT) in 'affected_rows' span attribute {pull}707[#707] * Add https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-traced[`@Traced`] annotation which either creates a span or a transaction, depending on the context * Report JMS destination as a span/transaction context field {pull}906[#906] * Added https://www.elastic.co/guide/en/apm/agent/java/master/config-jmx.html#config-capture-jmx-metrics[`capture_jmx_metrics`] configuration option [float] ===== Bug Fixes * JMS creates polling transactions even when the API invocations return without a message * Support registering MBeans which are added after agent startup [[release-notes-1.10.0]] ==== 1.10.0 - 2019/09/30 [float] ===== Features * Add ability to manually specify reported https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-hostname[hostname] * Add support for https://www.elastic.co/guide/en/apm/agent/java/master/supported-technologies-details.html#supported-databases[Redis Jedis client] * Add support for identifying target JVM to attach apm agent to using JVM property. See also the documentation of the <> * Added https://www.elastic.co/guide/en/apm/agent/java/master/config-jmx.html#config-capture-jmx-metrics[`capture_jmx_metrics`] configuration option * Improve servlet error capture {pull}812[#812] Among others, now also takes Spring MVC `@ExceptionHandler`s into account * Instrument Logger#error(String, Throwable) {pull}821[#821] Automatically captures exceptions when calling `logger.error(""message"", exception)` * Easier log correlation with https://github.com/elastic/java-ecs-logging. See https://www.elastic.co/guide/en/apm/agent/java/master/log-correlation.html[docs]. * Avoid creating a temp agent file for each attachment {pull}859[#859] * Instrument `View#render` instead of `DispatcherServlet#render` {pull}829[#829] This makes the transaction breakdown graph more useful. Instead of `dispatcher-servlet`, the graph now shows a type which is based on the view name, for example, `FreeMarker` or `Thymeleaf`. [float] ===== Bug Fixes * Error in log when setting https://www.elastic.co/guide/en/apm/agent/java/current/config-reporter.html#config-server-urls[server_urls] to an empty string - `co.elastic.apm.agent.configuration.ApmServerConfigurationSource - Expected previousException not to be null` * Avoid terminating the TCP connection to APM Server when polling for configuration updates {pull}823[#823] [[release-notes-1.9.0]] ==== 1.9.0 - 2019/08/22 [float] ===== Features * Upgrading supported OpenTracing version from 0.31 to 0.33 * Added annotation and meta-annotation matching support for `trace_methods`, for example: ** `public @java.inject.* org.example.*` (for annotation) ** `public @@javax.enterprise.context.NormalScope org.example.*` (for meta-annotation) * The runtime attachment now also works when the `tools.jar` or the `jdk.attach` module is not available. This means you don't need a full JDK installation - the JRE is sufficient. This makes the runtime attachment work in more environments such as minimal Docker containers. Note that the runtime attachment currently does not work for OSGi containers like those used in many application servers such as JBoss and WildFly. See the https://www.elastic.co/guide/en/apm/agent/java/master/setup-attach-cli.html[documentation] for more information. * Support for Hibernate Search [float] ===== Bug Fixes * A warning in logs saying APM server is not available when using 1.8 with APM server 6.x. Due to that, agent 1.8.0 will silently ignore non-string labels, even if used with APM server of versions 6.7.x or 6.8.x that support such. If APM server version is <6.7 or 7.0+, this should have no effect. Otherwise, upgrade the Java agent to 1.9.0+. * `ApacheHttpAsyncClientInstrumentation` matching increases startup time considerably * Log correlation feature is active when `active==false` * Tomcat's memory leak prevention mechanism is causing a... memory leak. JDBC statement map is leaking in Tomcat if the application that first used it is undeployed/redeployed. See https://discuss.elastic.co/t/elastic-apm-agent-jdbchelper-seems-to-use-a-lot-of-memory/195295[this related discussion]. [float] ==== Breaking Changes * The `apm-agent-attach.jar` is not executable anymore. Use `apm-agent-attach-standalone.jar` instead. [[release-notes-1.8.0]] ==== 1.8.0 - 2019/07/30 [float] ===== Features * Added support for tracking https://www.elastic.co/guide/en/kibana/7.3/transactions.html[time spent by span type]. Can be disabled by setting https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-breakdown-metrics[`breakdown_metrics`] to `false`. * Added support for https://www.elastic.co/guide/en/kibana/7.3/agent-configuration.html[central configuration]. Can be disabled by setting https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-central-config[`central_config`] to `false`. * Added support for Spring's JMS flavor - instrumenting `org.springframework.jms.listener.SessionAwareMessageListener` * Added support to legacy ApacheHttpClient APIs (which adds support to Axis2 configured to use ApacheHttpClient) * Added support for setting https://www.elastic.co/guide/en/apm/agent/java/1.x/config-reporter.html#config-server-urls[`server_urls`] dynamically via properties file {pull}723[#723] * Added https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-config-file[`config_file`] option * Added option to use `@javax.ws.rs.Path` value as transaction name https://www.elastic.co/guide/en/apm/agent/java/current/config-jax-rs.html#config-use-jaxrs-path-as-transaction-name[`use_jaxrs_path_as_transaction_name`] * Instrument quartz jobs https://www.elastic.co/guide/en/apm/agent/java/current/supported-technologies-details.html#supported-scheduling-frameworks[docs] * SQL parsing improvements {pull}696[#696] * Introduce priorities for transaction name {pull}748[#748]. Now uses the path as transaction name if https://www.elastic.co/guide/en/apm/agent/java/current/config-http.html#config-use-path-as-transaction-name[`use_path_as_transaction_name`] is set to `true` rather than `ServletClass#doGet`. But if a name can be determined from a high level framework, like Spring MVC, that takes precedence. User-supplied names from the API always take precedence over any others. * Use JSP path name as transaction name as opposed to the generated servlet class name {pull}751[#751] [float] ===== Bug Fixes * Some JMS Consumers and Producers are filtered due to class name filtering in instrumentation matching * Jetty: When no display name is set and context path is ""/"" transaction service names will now correctly fall back to configured values * JDBC's `executeBatch` is not traced * Drops non-String labels when connected to APM Server < 6.7 to avoid validation errors {pull}687[#687] * Parsing container ID in cloud foundry garden {pull}695[#695] * Automatic instrumentation should not override manual results {pull}752[#752] [float] ===== Breaking changes * The log correlation feature does not add `span.id` to the MDC anymore but only `trace.id` and `transaction.id` {pull}742[#742]. [[release-notes-1.7.0]] ==== 1.7.0 - 2019/06/13 [float] ===== Features * Added the `trace_methods_duration_threshold` config option. When using the `trace_methods` config option with wild cards, this enables considerable reduction of overhead by limiting the number of spans captured and reported (see more details in config documentation). NOTE: Using wildcards is still not the recommended approach for the `trace_methods` feature. * Add `Transaction#addCustomContext(String key, String|Number|boolean value)` to public API * Added support for AsyncHttpClient 2.x * Added https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-global-labels[`global_labels`] configuration option. This requires APM Server 7.2+. * Added basic support for JMS- distributed tracing for basic scenarios of `send`, `receive`, `receiveNoWait` and `onMessage`. Both Queues and Topics are supported. Async `send` APIs are not supported in this version. NOTE: This feature is currently marked as ""experimental"" and is disabled by default. In order to enable, it is required to set the https://www.elastic.co/guide/en/apm/agent/java/1.x/config-core.html#config-disable-instrumentations[`disable_instrumentations`] configuration property to an empty string. * Improved OSGi support: added a configuration option for `bootdelegation` packages {pull}641[#641] * Better span names for SQL spans. For example, `SELECT FROM user` instead of just `SELECT` {pull}633[#633] [float] ===== Bug Fixes * ClassCastException related to async instrumentation of Pilotfish Executor causing thread hang (applied workaround) * NullPointerException when computing Servlet transaction name with null HTTP method name * FileNotFoundException when trying to find implementation version of jar with encoded URL * NullPointerException when closing Apache AsyncHttpClient request producer * Fixes loading of `elasticapm.properties` for Spring Boot applications * Fix startup error on WebLogic 12.2.1.2.0 {pull}649[#649] * Disable metrics reporting and APM Server health check when active=false {pull}653[#653] [[release-notes-1.6.1]] ==== 1.6.1 - 2019/04/26 [float] ===== Bug Fixes * Fixes transaction name for non-sampled transactions https://github.com/elastic/apm-agent-java/issues/581[#581] * Makes log_file option work again https://github.com/elastic/apm-agent-java/issues/594[#594] * Async context propagation fixes ** Fixing some async mechanisms lifecycle issues https://github.com/elastic/apm-agent-java/issues/605[#605] ** Fixes exceptions when using WildFly managed executor services https://github.com/elastic/apm-agent-java/issues/589[#589] ** Exclude glassfish Executor which does not permit wrapped runnables https://github.com/elastic/apm-agent-java/issues/596[#596] ** Exclude DumbExecutor https://github.com/elastic/apm-agent-java/issues/598[#598] * Fixes Manifest version reading error to support `jar:file` protocol https://github.com/elastic/apm-agent-java/issues/601[#601] * Fixes transaction name for non-sampled transactions https://github.com/elastic/apm-agent-java/issues/597[#597] * Fixes potential classloader deadlock by preloading `FileSystems.getDefault()` https://github.com/elastic/apm-agent-java/issues/603[#603] [[release-notes-1.6.0]] ==== 1.6.0 - 2019/04/16 [float] ===== Related Announcements * Java APM Agent became part of the Cloud Foundry Java Buildpack as of https://github.com/cloudfoundry/java-buildpack/releases/tag/v4.19[Release v4.19] [float] ===== Features * Support Apache HttpAsyncClient - span creation and cross-service trace context propagation * Added the `jvm.thread.count` metric, indicating the number of live threads in the JVM (daemon and non-daemon) * Added support for WebLogic * Added support for Spring `@Scheduled` and EJB `@Schedule` annotations - https://github.com/elastic/apm-agent-java/pull/569[#569] [float] ===== Bug Fixes * Avoid that the agent blocks server shutdown in case the APM Server is not available - https://github.com/elastic/apm-agent-java/pull/554[#554] * Public API annotations improper retention prevents it from being used with Groovy - https://github.com/elastic/apm-agent-java/pull/567[#567] * Eliminate side effects of class loading related to Instrumentation matching mechanism [[release-notes-1.5.0]] ==== 1.5.0 - 2019/03/26 [float] ===== Potentially breaking changes * If you didn't explicitly set the https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-name[`service_name`] previously and you are dealing with a servlet-based application (including Spring Boot), your `service_name` will change. See the documentation for https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-name[`service_name`] and the corresponding section in _Features_ for more information. Note: this requires APM Server 7.0+. If using previous versions, nothing will change. [float] ===== Features * Added property `""allow_path_on_hierarchy""` to JAX-RS plugin, to lookup inherited usage of `@path` * Support for number and boolean labels in the public API {pull}497[497]. This change also renames `tag` to `label` on the API level to be compliant with the https://github.com/elastic/ecs#-base-fields[Elastic Common Schema (ECS)]. The `addTag(String, String)` method is still supported but deprecated in favor of `addLabel(String, String)`. As of version 7.x of the stack, labels will be stored under `labels` in Elasticsearch. Previously, they were stored under `context.tags`. * Support async queries made by Elasticsearch REST client * Added `setStartTimestamp(long epochMicros)` and `end(long epochMicros)` API methods to `Span` and `Transaction`, allowing to set custom start and end timestamps. * Auto-detection of the `service_name` based on the `` element of the `web.xml` with a fallback to the servlet context path. If you are using a spring-based application, the agent will use the setting for `spring.application.name` for its `service_name`. See the documentation for https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-name[`service_name`] for more information. Note: this requires APM Server 7.0+. If using previous versions, nothing will change. * Previously, enabling https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-capture-body[`capture_body`] could only capture form parameters. Now it supports all UTF-8 encoded plain-text content types. The option https://www.elastic.co/guide/en/apm/agent/java/master/config-http.html#config-capture-body-content-types[`capture_body_content_types`] controls which `Content-Type`s should be captured. * Support async calls made by OkHttp client (`Call#enqueue`) * Added support for providing config options on agent attach. ** CLI example: `--config server_urls=http://localhost:8200,http://localhost:8201` ** API example: `ElasticApmAttacher.attach(Map.of(""server_urls"", ""http://localhost:8200,http://localhost:8201""));` [float] ===== Bug Fixes * Logging integration through MDC is not working properly - https://github.com/elastic/apm-agent-java/issues/499[#499] * ClassCastException with adoptopenjdk/openjdk11-openj9 - https://github.com/elastic/apm-agent-java/issues/505[#505] * Span count limitation is not working properly - reported https://discuss.elastic.co/t/kibana-apm-not-showing-spans-which-are-visible-in-discover-too-many-spans/171690[in our forum] * Java agent causes Exceptions in Alfresco cluster environment due to failure in the instrumentation of Hazelcast `Executor`s - reported https://discuss.elastic.co/t/cant-run-apm-java-agent-in-alfresco-cluster-environment/172962[in our forum] [[release-notes-1.4.0]] ==== 1.4.0 - 2019/02/14 [float] ===== Features * Added support for sync calls of OkHttp client * Added support for context propagation for `java.util.concurrent.ExecutorService`s * The `trace_methods` configuration now allows to omit the method matcher. Example: `com.example.*` traces all classes and methods within the `com.example` package and sub-packages. * Added support for JSF. Tested on WildFly, WebSphere Liberty and Payara with embedded JSF implementation and on Tomcat and Jetty with MyFaces 2.2 and 2.3 * Introduces a new configuration option `disable_metrics` which disables the collection of metrics via a wildcard expression. * Support for HttpUrlConnection * Adds `subtype` and `action` to spans. This replaces former typing mechanism where type, subtype and action were all set through the type in an hierarchical dotted-syntax. In order to support existing API usages, dotted types are parsed into subtype and action, however `Span.createSpan` and `Span.setType` are deprecated starting this version. Instead, type-less spans can be created using the new `Span.startSpan` API and typed spans can be created using the new `Span.startSpan(String type, String subtype, String action)` API * Support for JBoss EAP 6.4, 7.0, 7.1 and 7.2 * Improved startup times * Support for SOAP (JAX-WS). SOAP client create spans and propagate context. Transactions are created for `@WebService` classes and `@WebMethod` methods. [float] ===== Bug Fixes * Fixes a failure in BitBucket when agent deployed https://github.com/elastic/apm-agent-java/issues/349[#349] * Fixes increased CPU consumption https://github.com/elastic/apm-agent-java/issues/453[#453] and https://github.com/elastic/apm-agent-java/issues/443[#443] * Fixed some OpenTracing bridge functionalities that were not working when auto-instrumentation is disabled * Fixed an error occurring when ending an OpenTracing span before deactivating * Sending proper `null` for metrics that have a NaN value * Fixes JVM crash with Java 7 https://github.com/elastic/apm-agent-java/issues/458[#458] * Fixes an application deployment failure when using EclipseLink and `trace_methods` configuration https://github.com/elastic/apm-agent-java/issues/474[#474] [[release-notes-1.3.0]] ==== 1.3.0 - 2019/01/10 [float] ===== Features * The agent now collects system and JVM metrics https://github.com/elastic/apm-agent-java/pull/360[#360] * Add API methods `ElasticApm#startTransactionWithRemoteParent` and `Span#injectTraceHeaders` to allow for manual context propagation https://github.com/elastic/apm-agent-java/pull/396[#396]. * Added `trace_methods` configuration option which lets you define which methods in your project or 3rd party libraries should be traced. To create spans for all `public` methods of classes whose name ends in `Service` which are in a sub-package of `org.example.services` use this matcher: `public org.example.services.*.*Service#*` https://github.com/elastic/apm-agent-java/pull/398[#398] * Added span for `DispatcherServlet#render` https://github.com/elastic/apm-agent-java/pull/409[#409]. * Flush reporter on shutdown to make sure all recorded Spans are sent to the server before the program exits https://github.com/elastic/apm-agent-java/pull/397[#397] * Adds Kubernetes https://github.com/elastic/apm-agent-java/issues/383[#383] and Docker metadata to, enabling correlation with the Kibana Infra UI. * Improved error handling of the Servlet Async API https://github.com/elastic/apm-agent-java/issues/399[#399] * Support async API’s used with AsyncContext.start https://github.com/elastic/apm-agent-java/issues/388[#388] [float] ===== Bug Fixes * Fixing a potential memory leak when there is no connection with APM server * Fixes NoSuchMethodError CharBuffer.flip() which occurs when using the Elasticsearch RestClient and Java 7 or 8 https://github.com/elastic/apm-agent-java/pull/401[#401] [[release-notes-1.2.0]] ==== 1.2.0 - 2018/12/19 [float] ===== Features * Added `capture_headers` configuration option. Set to `false` to disable capturing request and response headers. This will reduce the allocation rate of the agent and can save you network bandwidth and disk space. * Makes the API methods `addTag`, `setName`, `setType`, `setUser` and `setResult` fluent, so that calls can be chained. [float] ===== Bug Fixes * Catch all errors thrown within agent injected code * Enable public APIs and OpenTracing bridge to work properly in OSGi systems, fixes https://github.com/elastic/apm-agent-java/issues/362[this WildFly issue] * Remove module-info.java to enable agent working on early Tomcat 8.5 versions * Fix https://github.com/elastic/apm-agent-java/issues/371[async Servlet API issue] [[release-notes-1.1.0]] ==== 1.1.0 - 2018/11/28 [float] ===== Features * Some memory allocation improvements * Enabling bootdelegation for agent classes in Atlassian OSGI systems [float] ===== Bug Fixes * Update dsl-json which fixes a memory leak. See https://github.com/ngs-doo/dsl-json/pull/102[ngs-doo/dsl-json#102] for details. * Avoid `VerifyError`s by non instrumenting classes compiled for Java 4 or earlier * Enable APM Server URL configuration with path (fixes #339) * Reverse `system.hostname` and `system.platform` order sent to APM server [[release-notes-1.0.1]] ==== 1.0.1 - 2018/11/15 [float] ===== Bug Fixes * Fixes NoSuchMethodError CharBuffer.flip() which occurs when using the Elasticsearch RestClient and Java 7 or 8 {pull}313[#313] [[release-notes-1.0.0]] ==== 1.0.0 - 2018/11/14 [float] ===== Breaking changes * Remove intake v1 support. This version requires APM Server 6.5.0+ which supports the intake api v2. Until the time the APM Server 6.5.0 is officially released, you can test with docker by pulling the APM Server image via `docker pull docker.elastic.co/apm/apm-server:6.5.0-SNAPSHOT`. [float] ===== Features * Adds `@CaptureTransaction` and `@CaptureSpan` annotations which let you declaratively add custom transactions and spans. Note that it is required to configure the `application_packages` for this to work. See the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-annotation[documentation] for more information. * The public API now supports to activate a span on the current thread. This makes the span available via `ElasticApm#currentSpan()` Refer to the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-span-activate[documentation] for more details. * Capturing of Elasticsearch RestClient 5.0.2+ calls. Currently, the `*Async` methods are not supported, only their synchronous counterparts. * Added API methods to enable correlating the spans created from the JavaScrip Real User Monitoring agent with the Java agent transaction. More information can be found in the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-ensure-parent-id[documentation]. * Added `Transaction.isSampled()` and `Span.isSampled()` methods to the public API * Added `Transaction#setResult` to the public API {pull}293[#293] [float] ===== Bug Fixes * Fix for situations where status code is reported as `200`, even though it actually was `500` {pull}225[#225] * Capturing the username now properly works when using Spring security {pull}183[#183] [[release-notes-1.0.0.rc1]] ==== 1.0.0.RC1 - 2018/11/06 [float] ===== Breaking changes * Remove intake v1 support. This version requires APM Server 6.5.0+ which supports the intake api v2. Until the time the APM Server 6.5.0 is officially released, you can test with docker by pulling the APM Server image via `docker pull docker.elastic.co/apm/apm-server:6.5.0-SNAPSHOT`. * Wildcard patterns are case insensitive by default. Prepend `(?-i)` to make the matching case sensitive. [float] ===== Features * Support for Distributed Tracing * Adds `@CaptureTransaction` and `@CaptureSpan` annotations which let you declaratively add custom transactions and spans. Note that it is required to configure the `application_packages` for this to work. See the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-annotation[documentation] for more information. * The public API now supports to activate a span on the current thread. This makes the span available via `ElasticApm#currentSpan()` Refer to the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-span-activate[documentation] for more details. * Capturing of Elasticsearch RestClient 5.0.2+ calls. Currently, the `*Async` methods are not supported, only their synchronous counterparts. * Added API methods to enable correlating the spans created from the JavaScrip Real User Monitoring agent with the Java agent transaction. More information can be found in the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-ensure-parent-id[documentation]. * Microsecond accurate timestamps {pull}261[#261] * Support for JAX-RS annotations. Transactions are named based on your resources (`ResourceClass#resourceMethod`). [float] ===== Bug Fixes * Fix for situations where status code is reported as `200`, even though it actually was `500` {pull}225[#225] [[release-notes-0.8.x]] === Java Agent version 0.8.x [[release-notes-0.8.0]] ==== 0.8.0 [float] ===== Breaking changes * Wildcard patterns are case insensitive by default. Prepend `(?-i)` to make the matching case sensitive. [float] ===== Features * Wildcard patterns are now not limited to only one wildcard in the middle and can be arbitrarily complex now. Example: `*foo*bar*baz`. * Support for JAX-RS annotations. Transactions are named based on your resources (`ResourceClass#resourceMethod`). [[release-notes-0.7.x]] === Java Agent version 0.7.x [[release-notes-0.7.1]] ==== 0.7.1 - 2018/10/24 [float] ===== Bug Fixes * Avoid recycling transactions twice {pull}178[#178] [[release-notes-0.7.0]] ==== 0.7.0 - 2018/09/12 [float] ===== Breaking changes * Removed `ElasticApm.startSpan`. Spans can now only be created from their transactions via `Transaction#createSpan`. * `ElasticApm.startTransaction` and `Transaction#createSpan` don't activate the transaction and spans and are thus not available via `ElasticApm.activeTransaction` and `ElasticApm.activeSpan`. [float] ===== Features * Public API ** Add `Span#captureException` and `Transaction#captureException` to public API. `ElasticApm.captureException` is deprecated now. Use `ElasticApm.currentSpan().captureException(exception)` instead. ** Added `Transaction.getId` and `Span.getId` methods * Added support for async servlet requests * Added support for Payara/Glassfish * Incubating support for Apache HttpClient * Support for Spring RestTemplate * Added configuration options `use_path_as_transaction_name` and `url_groups`, which allow to use the URL path as the transaction name. As that could contain path parameters, like `/user/$userId` however, You can set the `url_groups` option to define a wildcard pattern, like `/user/*`, to group those paths together. This is especially helpful when using an unsupported Servlet API-based framework. * Support duration suffixes (`ms`, `s` and `m`) for duration configuration options. Not using the duration suffix logs out a deprecation warning and will not be supported in future versions. * Add ability to add multiple APM server URLs, which enables client-side load balancing. The configuration option `server_url` has been renamed to `server_urls` to reflect this change. However, `server_url` still works for backwards compatibility. * The configuration option `service_name` is now optional. It defaults to the main class name, the name of the executed jar file (removing the version number), or the application server name (for example `tomcat-application`). In a lot of cases, you will still want to set the `service_name` explicitly. But it helps getting started and seeing data easier, as there are no required configuration options anymore. In the future we will most likely determine more useful application names for Servlet API-based applications. ",16210,True,3202.2036597019614,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; /** * This method will be called when we see '/*' and try to match it as a bracketed comment. * If the next character is '+', it should be parsed as hint later, and we cannot match * it as a bracketed comment. * * Returns true if the next character is '+'. */ public boolean isHint() { int nextChar = _input.LA(1); if (nextChar == '+') { return true; } else { return false; } } } singleStatement : statement ';'* EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE namespace (IF NOT EXISTS)? multipartIdentifier (commentSpec | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER namespace multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER namespace multipartIdentifier SET locationSpec #setNamespaceLocation | DROP namespace (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (commentSpec | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier alterColumnAction? #alterTableAlterColumn | ALTER TABLE table=multipartIdentifier partitionSpec? CHANGE COLUMN? colName=multipartIdentifier colType colPosition? #hiveChangeColumn | ALTER TABLE table=multipartIdentifier partitionSpec? REPLACE COLUMNS '(' columns=qualifiedColTypeWithPositionList ')' #hiveReplaceColumns | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? (commentSpec | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) ns=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) ns=multipartIdentifier)? #showColumns | SHOW VIEWS ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showViews | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier (AS SERDE)? #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) namespace EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeRelation | (DESC | DESCRIBE) QUERY? query #describeQuery | COMMENT ON namespace multipartIdentifier IS comment=(STRING | NULL) #commentNamespace | COMMENT ON TABLE multipartIdentifier IS comment=(STRING | NULL) #commentTable | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier (STRING | .*?) #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; commentSpec : COMMENT STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; namespace : NAMESPACE | DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; createTableClauses :((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | commentSpec | (TBLPROPERTIES tableProps=tablePropertyList))* ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier commentSpec? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=RLIKE pattern=valueExpression | NOT? kind=LIKE quantifier=(ANY | SOME | ALL) ('('')' | '(' expression (',' expression)* ')') | NOT? kind=LIKE pattern=valueExpression (ESCAPE escapeChar=STRING)? | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | FIRST '(' expression (IGNORE NULLS)? ')' #first | LAST '(' expression (IGNORE NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (FILTER '(' WHERE where=booleanExpression ')')? (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | HOUR | MINUTE | MONTH | SECOND | YEAR | identifier ; colPosition : position=FIRST | position=AFTER afterCol=errorCapturingIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (NOT NULL)? commentSpec? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (NOT NULL)? commentSpec? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (NOT NULL)? commentSpec? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | FILTER | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; alterColumnAction : TYPE dataType | commentSpec | colPosition | setOrDrop=(SET | DROP) NOT NULL ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `EXPLAIN SELECT ...` is a command, but EXPLAIN // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved //--ANSI-NON-RESERVED-START : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | VIEWS | WINDOW //--ANSI-NON-RESERVED-END ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPE | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FILTER | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MINUTE | MONTH | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | VIEWS | WHEN | WHERE | WINDOW | WITH | YEAR ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ //--SPARK-KEYWORD-LIST-START ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILTER: 'FILTER'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; VIEWS: 'VIEWS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; //--SPARK-KEYWORD-LIST-END //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ('\\\\\\n' | ~[\\r\\n])* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' {!isHint()}? (BRACKETED_COMMENT|.)*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12525,False,2338.664086361021,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, ANSI SQL parsing mode is enabled. */ public boolean ansi = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; singleInterval : INTERVAL? (intervalValue intervalUnit)+ EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER database db=errorCapturingIdentifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | ALTER database db=errorCapturingIdentifier SET locationSpec #setDatabaseLocation | DROP (database | NAMESPACE) (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE multipartIdentifier RENAME COLUMN from=qualifiedName TO to=identifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=qualifiedNameList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=qualifiedNameList #dropTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE multipartIdentifier (ALTER | CHANGE) COLUMN? qualifiedName (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE tableIdentifier partitionSpec? CHANGE COLUMN? colName=errorCapturingIdentifier colType colPosition? #changeColumn | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER TABLE tableIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER VIEW tableIdentifier ADD (IF NOT EXISTS)? partitionSpec+ #addTablePartition | ALTER TABLE tableIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER TABLE tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER VIEW tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW tableIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? qualifiedName AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? qualifiedName #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=errorCapturingIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) namespace=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (qualifiedName | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) database EXTENDED? db=errorCapturingIdentifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING qualifiedName ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assign (',' assign)* ; assign : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | IDENTIFIER '->' expression #lambda | '(' IDENTIFIER (',' IDENTIFIER)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : {ansi}? INTERVAL? intervalField+ | {!ansi}? INTERVAL intervalField* ; intervalField : value=intervalValue unit=intervalUnit (TO to=intervalUnit)? ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER qualifiedName ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=qualifiedName dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!ansi}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {ansi}? ansiNonReserved #unquotedIdentifier | {!ansi}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `spark.sql.ansi.enabled=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `spark.sql.ansi.enabled=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `spark.sql.ansi.enabled=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12071,False,2259.2130184141997,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER (database | NAMESPACE) multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER (database | NAMESPACE) multipartIdentifier SET locationSpec #setNamespaceLocation | DROP (database | NAMESPACE) (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier tableProvider? locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) namespace=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) namespace=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) (database | NAMESPACE) EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? | {SQL_standard_keyword_behavior}? (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval) ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER multipartIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12363,False,2312.642303230286,median "<%@ Control Language=""C#"" AutoEventWireup=""true"" CodeBehind=""DocumetaryCollection.ascx.cs"" Inherits=""BankProject.TradingFinance.Import.DocumentaryCollections.DocumetaryCollection"" %> <%@ Register Assembly=""Telerik.Web.UI"" Namespace=""Telerik.Web.UI"" TagPrefix=""telerik"" %> <%@ Register Src=""../../../Controls/VVTextBox.ascx"" TagPrefix=""uc1"" TagName=""VVTextBox"" %>
 

Cancel Date
Contingent Expiry Date
Cancel Remark
Accepted Date
Remarks
Remitting Bank Information
Collection Type (*)
Id Description
<%# DataBinder.Eval(Container.DataItem, ""Id"")%> <%# DataBinder.Eval(Container.DataItem, ""Description"")%>
Remitting Type
Remitting Bank No
Remitting Bank Addr.
Remitting Bank Addr.
Remitting Bank Addr.
Remitting Bank Acct
Remitting Bank Ref (*)
Drawee Information
Drawee Type
Drawee Cus No
Customer Id Customer Name
<%# DataBinder.Eval(Container.DataItem, ""CustomerID"")%> <%# DataBinder.Eval(Container.DataItem, ""CustomerName2"")%>
Drawee Cus Name
Drawee Addr.
Drawee Addr.
Drawee Addr.
Reimb Drawee Acct
Drawer Details
Drawer Type
Drawer Cus No.
Drawer Cus Name
Drawer Addr.
Drawer Addr.
Drawer Addr.
General Collection Information
Currency (*)
Amount (*)
Amount Old
Docs Received Date
Maturity Date
Tenor
Days
Tracer Date
Reminder Days
Account Officer
Commodity (*)
Id Description
<%# DataBinder.Eval(Container.DataItem, ""ID"")%> <%# DataBinder.Eval(Container.DataItem, ""Name"")%>
Docs Code Add more
No. of Originals
No. of Copies
Docs Code <%--
Id Description
<%# DataBinder.Eval(Container.DataItem, ""Id"")%> <%# DataBinder.Eval(Container.DataItem, ""Description"")%>
--%>
No. of Originals
No. of Copies
Other Docs
Instruction to Cus
Remarks
Other Infor
Express No
Invoice No
<%= TabId == 281 ? ""Create MT412"" : ""Create MT410"" %>
General MT 410/MTx99?
Sending Bank's TRN
Related Reference
Currency Code
Amount
Charge Details
Waive Charges
Charge code
Charge Currency
Charge Acct
Id Name
<%# DataBinder.Eval(Container.DataItem, ""Id"")%> <%# DataBinder.Eval(Container.DataItem, ""Name"")%>
Charge Period
Exch. Rate
Charge Amt
Party Charged
Amort Charges
Amt. In Local CCY
Amt DR from Acct
Charge Status
Charge code
Charge Currency
<%----%>
Charge Acct
Id Name
<%# DataBinder.Eval(Container.DataItem, ""Id"")%> <%# DataBinder.Eval(Container.DataItem, ""Name"")%>
Charge Period
Exch. Rate
Charge Amt
Party Charged
Amort Charges
Amt. In Local CCY
Amt DR from Acct
Charge Status
Charge Remarks
VAT No
<%-- <%if (TabId != 281) {%>--%> <%--<% } %>--%>
Tax Code
Tax Ccy
Tax Amt
Tax in LCCY Amt
Tax Date
<%--<%if (TabId != 281) {%>--%> <%--<% } %>--%>
Tax Code
Tax Ccy
Tax Amt
Tax in LCCY Amt
Tax Date
<%--
--%>
",16352,True,3487.58464694039,median "<%@ Page Language=""C#"" AutoEventWireup=""true"" CodeBehind=""SalivaReport.aspx.cs"" Inherits=""abundalife1001.SalivaReport"" %> Abunda Life Medical Nutrition Testing Clinic
<%--
Naturopathic Abunda Life 1001
Nutritional Testing & Personal Health Evaluation
--%>
<%--
Patient Name:
Date:
--%>
For: 
Date: 
In House Urine/Saliva Tests

Sugar Refractometer Test

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

2.2 - 4.2 2.2 - 5.9 Show Result

Sugar Refractometer stand alone indicators generally associated with:

Blood sugar and bio-energy.

Your score is ideal:

Generally associated with Low Sugar Refractometer:

Hypoglycemia, out of gas, mood swings.

Corresponding need for nutritional support for Low Sugar Refractometer:

Super Drink, Mega B Complex 1000, Stress & Tonic Protector, Pancreatian, 28 super Amino Acids, Super Oil Wheat Germ Oil, L-Arginine Complex, Chromium Picolonate, super Endurance, Alfalfa Juice, L-Carnitine, Co-Enzyme Q-10, Ionic Vanadium, Chromium, Germanium, Lithium, Gold, Selenium, Zinc.

Generally associated with High Sugar Refractometer:

Metabolic syndrome, early stage diabetes, metabolic acidosis, over use of medications, alcohol, sugar, trans fats, carbohydrates, devitalized food, over eating at one meal then going too long to next meal, cellular oxygen deficiency, lack of exercise, mal-absorption, excess body fat weight, syndrome X.

Corresponding need for nutritional support for High Sugar Refractometer:

Alpha Lipoic Acid, Golden Seal Root, Mega B Complex 1000, Co-Enzyme Q-10, Blood Sugar & Energy Stabilizing Formula, L-Cystein, L-Carnitine, L-Argine, Endurall, Ionic Chromium, Vanadium, Selenium, Pancreatin.

Vegetable Juice Concentrates:

Avocado, apple, zucchini

Support:

Pancreas, adrenals. (Homeopathic Remedies: #29, #32, #43, #818, #829)

Conductivity

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

6- 11 6 - 16 Show Result

Conductivity stand alone indicators generally associated with:

Toxicity, metabolic efficiency, cellular hydration, electrolyte, mineral gauge, metabolic efficiency, body fat storing or burning indicator.

Your score is ideal:

Generally associated with Low Conductivity:

Electrolyte imbalance, over hydration, mineral depletion.

Corresponding need for nutritional support for Low Conductivity:

Irish Moss/Kelp, Sea Vegetable Extract Tonic, Ionic Potassium, Magnesium, Calcium.

Generally associated with High Conductivity:

Sub-clinical dehydration, autointoxication, metabolic acidosis, lymphatic congestion, cells holding toxic fluids, cellular oxygen deficiency, over use of medications, birth control pills, antibiotics, aspirin type substances, coffee, soda, sugar, devitalized foods, over eating, lack of exercise, excess body fat, mal-absorption, constipation, mineral deficiency, electrolyte imbalance.

Corresponding need for nutritional support for High Conductivity:

Jug One Protocol, Green Drink, Bedtime Bowel Tonic.

Vegetable Juice Concentrates:

Apple, zucchini, celery, parsley.

Support:

Posterior pituitary, kidneys, lymphatic system. (Homeopathic Remedies: #817, #823)

Nitrate Nitrogen

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

2 - 4 1 - 5 Show Result

Nitrate Nitrogen stand alone indicators generally associated with:

Protein utilization, food transition time, toxicity, general overall health status.

Your score is ideal:

Generally associated with Low Nitrate Nitrogen:

Low is desirable. Zero is ideal.

Generally associated with High Nitrate Nitrogen:

Highly toxic condition, mal-absorption, hypochlorhydria, dirty colon.

Corresponding need for nutritional support for High Nitrate Nitrogen:

Morning Health Drink, Jug One Protocol, Green Drink, Bedtime Bowel Tonic, Maxi Cleanse, Fiber Max.

Vegetable Juice Concentrates:

Spinach, fig, plum.

Support:

Liver, colon. (Homeopathic Remedies: #8, #10, #40, #63, #819)

Ammonical Nitrogen

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

2 - 4 1 - 5 Show Result

Ammonical Nitrogen stand alone indicators generally associated with:

Amino acid digestion, food transition time, toxicity, general health status.

Your score is ideal:

Generally associated with Low Ammonical Nitrogen:

Low is desirable. Zero is ideal.

Generally associated with High Ammonical Nitrogen:

Poor protein to amino acid conversion, autointoxication, dirty colon.

Corresponding need for nutritional support for High Ammonical Nitrogen:

Jug One Protocol, Green Drink, Bedtime Bowel Tonic.

Vegetable Juice Concentrates:

Lemon, spinach, kale, fig, plum

Support:

Digestion, liver, colon. (Homeopathic Remedies; #7, #8, #10, #820)

Indican

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

300 - 600 250 - 750 Show Result

Indican stand alone indicators generally associated with:

Colon health, bowel toxicity, efficient food transition, autointoxication.

Your score is ideal:

Generally associated with Low Indican:

Low is desirable.

Generally associated with High Indican:

Colon toxicity, constipation (having less than a bowel movement for each meal that you eat), toxins backing up into cells, immune system being over run, lymphatic congestion, energy being diverted to neutralize toxins, bouts with physical and mental fatigue, bloating, toxic fluid retention, excess body fat, autointoxication.

Corresponding need for nutritional support for High Indican:

Jug One Protocol, Jug Two Protocol, Morning Health Drink, Yogurt Health Drink, Green Drink, Bedtime Bowel Tonic, Fiber Max, Maxi Cleanse.

Vegetable Juice Concentrates:

Spinach, broccoli, cauliflower, apple.

Support:

Detoxification. (Homeopathic Remedies: #40, #63, #819)

C-Reactive Protein

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

0 - 3 0 - 6 Show Result

C-Reactive Protein stand alone indicators generally associated with:

Inflammatory marker, after effect of the body, scavenger/clean up process, early warning marker of cardio-vascular disease, peripheral vascular disease, cellular breakdown, cancer, Alzheimer’s, early stage infection gauge

Your score is ideal:

Generally associated with Low C-Reactive Protein:

Low is desirable. Zero is ideal

Generally associated with High C-Reactive Protein:

Inflammatory and/or degenerative condition, excess sugar, constipation, cellular oxygen deficiency, toxicity, diabetes, mellitus, hypothyroidism, obstruction, pancreatitis, pregnancy, liver malfunction, early warning of cardio-vascular disease, future stroke, rheumatoid arthritis, cancer, T.B., pneumonia, SLE, Alzheimer’s, low grade infection, colon toxicity, bacteria infection, fungal condition, over use of medications, trapped lymphatic toxins

Corresponding need for nutritional support for High C-Reactive Protein:

Enzyme Therapy, L-Carnitine, L-Arginine Complex, Hawthorn Berry, Capsicum, Alpha Lipoic Acid, Co-Enzyme Q-10, Bromoline, Omega 3/6 Essential Fatty Acids, Wheat Germ Oil, Vitamin E Complex, Brain Flush, Lipotropic Factors, Phasphadtyl Choline, Duo C Complex, Green Drink, Green Tea Extract, Immune Power Formula, N-Acetyl Cysteine, Turmeric.

Vegetable Juice Concentrates:

Spinach, avocado, mushroom, broccoli, cauliflower

Support:

Cardio-vascular system, immune system, brain. (Homeopathic Remedies: #66, #807, #814, #825)

Homocysteine

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

0 - 7 4.0 - 15.4 Show Result

Homocysteine stand alone indicators generally associated with:

Early warning stroke, cardio-vascular disease, cancer, Alzheimer’s.

Your score is ideal:

Generally associated with Low Homocysteine:

Mal-absorption syndrome, deficiencies in enzymes and proteins, homeopathic remedies: #18, #29, #32, #805

Corresponding need for nutritional support for Low Homocysteine:

Cysteine, Methionine, L-Carnitine, L-Glutamine, L-Arginine.

Generally associated with High Homocysteine:

Inflammation, 100 times more predictive than cholesterol for cardio-vascular disease, lack of fitness, early warnings of stroke, cancer, Alzheimer’s, depression, dementia, arterial stiffness, repressed anger.

Corresponding need for nutritional support for High Homocysteine:

Vitamin B Complex, Vitamin B-12, Co-Enzyme Q-10, L-Arginine, Zinc, DMG, L-Carnitine, Folic Acid, Pyridoxine, Enzymes Therapy

Clinical Treatments Indicated:

I.V. Super Nutritional Drip, Naturopathic Detoxification, Nutritional Saturation Therapy

Vegetable Juice Concentrates:

Celery, zucchini, spinach, avocado, mushroom.

Support:

Cardio-vascular system, brain. (Homeopathic Remedies: #43, #812, #814, #825)

Lactic Acid

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

0 - 9.5 4.5 - 1.8 Show Result

Lactic Acid stand alone indicators generally associated with:

Level of oxygen at cell level.

Your score is ideal:

Generally associated with Low Lactic Acid:

Low is desirable. Zero is ideal

Generally associated with High Lactic Acid:

Cellular oxygen deficiency, precursor to metabolic acidosis, the environment necessary for Candida, fungal, yeast, viral parasite, bacteria infections, autointoxication, chronic fatigue syndrome, muscle fatigue, low fitness level, slow repair, sore muscles, sluggish metabolism, excess body fat accumulation, mal-absorption, skin disorders, brain fog, forgetfulness, inability to cooperate, broken brain disorders, premature aging, early warning of degenerative disease, stroke, heart disease, immune system vulnerability, low tolerance to stress, depression disorientation, exhaustion, pre cancer warning

Corresponding need for nutritional support for High Lactic Acid:

Green Drink, L-Arginine Complex, L-Carnitine, Co-Enzyme Q-10, Vitamin E Complex, Wheat Germ Oil

Vegetable Juice Concentrates:

Beet, zucchini, spinach

Support:

Lungs, cardio-vascular, muscles. (Homeopathic Remedies: #825, #826)

Cortisol

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

7.2 - 17.2 4.3 - 22.4 Show Result

Cortisol stand alone indicators generally associated with:

Stress indicator, the effects of the mind and emotions are having on the organs, nerves, cells and immune system.

Your score is ideal:

Generally associated with Low Cortisol:

Hypoglycemia, hypotension, out of gas, adrenal exhaustion, chronic fatigue syndrome, connective tissue disease, depression, hypothyroid, allergies, suppressed immune system, loss of strength, psoriasis, nerve burn out, reduced work capacity, eczema, premature aging, anxiety, nervous exhaustion, rheumatoid and/or arthritic type conditions, hypopituitaryism, human growth hormone deficiency, multiple nutrition deficiency syndrome.

Corresponding need for nutritional support for Low Cortisol:

Adrenal Hormone Restoration, Royal Queen Bee Jelly, Macho Herba, Bio-Identical Hormone Restoration, Human Growth Hormone Restoration Therapy

Generally associated with High Cortisol:

Obesity, cancer, hypertension, deficiencies in magnesium, vitamin C, citrus bio-flavanoids, B complex, pantothemic acid, adrenal exhaustion, nervous breakdown, stressed out thyroid problems, nerves and body in a state of high alert, excess cortisol level due to worry, anxiety, stress, anger, fear, trauma, carcinoma, high blood pressure, high cholesterol, early warning heart disease, stroke, immune breakdown, G.I. type diseases.

Corresponding need for nutritional support for High Cortisol:

Nerve Builder, Mega B Complex 1000, Duo C Complex, Stress & Tonic Protector, Adrenal Hormone Restoration Factors, Pineal Hormone Restoration Factors, Cal/Mag, Hypericum, Valerian Root.

Vegetable Juice Concentrates:

Spinach, tomato, zucchini.

Support:

Nerves, brain, immune system. (Homeopathic Remedies: #17, #807, #812, #814)

Cortisol/ DHEA Ratio

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

188 - 433.4 659 - 5559 Show Result

Cortisol DHEA Ratio stand alone indicators generally associated with:

Stress, Anxiety, weight gain, exaustion, fatigue, low libido.

Your score is ideal:

Generally associated with Low Cortisol DHEA Ratio:

Anxiety

Generally associated with High Cortisol DHEA Ratio:

Wiped out

Insulin

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

0 - 6 6 - 27 Show Result

Insulin stand alone indicators generally associated with:

Insulin gauge, diabetes, hypoglycemia and metabolic syndrome, body fat weight gain

Your score is ideal:

Generally associated with Low Insulin:

Pancreatic insufficiency, hypopituitaryism, human growth hormone (HGH) deficiency

Corresponding need for nutritional support for Low Insulin:

L-Glutamine, L-Arginine, L-Carnitine, Pancreatin, Enzyme Therapy, Mega B complex 1000, Enzyme Therapy, Super Oil

Generally associated with High Insulin:

Insulin resistance, diabetes, stress tension, anxiety, excess sugar, junk foods, carbohydrates, medications, alcohol, obesity, lack of fitness, liver sluggishness, kidney disorder, early heart disease warning, hypertension and dyslipidema.

Corresponding need for nutritional support for High Insulin:

Mega B Complex 1000, Golden Seal Root, Gymena Sylvestre, RNA/DNA, Blood Sugar and Energy Stabilizer, Endurall, G.T.F. Factors, Super Food Drink, Licorice Root, Ginseng, Green Drink, 28 Super Amino Acids, L-Arginine Complex, Pancreatic, Adrenal Hormone Restoration Factors, Queen Bee Jelly, Alpha Lipoic Acid, Co-Enzyme Q-10, Thiamine, Magnesium, Potassium, Chromium.

Clinical Treatments Indicated:

Bio-Identical Hormone Restoration Therapy, I.V. Alpha Lipoic Acid Therapy, Fitness Medicine, Naturopathic Detoxification Ozone Therapy

Vegetable Juice Concentrates:

Zucchini, kale, broccoli, cauliflower.

Support:

Pancreas, adrenals. (Homeopathic Remedies; #818, #829)

Estrogen

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

Estrogen stand alone indicators generally associated with:

Your score is ideal:

Generally associated with Low estrogen:

Generally associated with High estrogen:

PSA - Men

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

2.9 4.0 Show Result

PSA stand alone indicators generally associated with:

Prostate health

Your score is ideal:

Generally associated with Low PSA:

Low is desirable. Zero is ideal

Generally associated with High PSA:

Prostatitis, benign enlarged prostate, lower spine subluxation, constipation, zinc deficiency, prostate cancer, urinary tract infection, impacted colon

Corresponding need for nutritional support for High PSA:

San Palmetto, PSA, Cranberry Juice Concentrate, Co-Enzyme Q-10, Vitamin E Complex, Wheat Germ Oil, Super Oil, Omega 3/6 Essential Fatty Acids, Duo C Complex, Green Drink, Bowel Tonic, Turmeric, Ionic Zinc, Cobalt, Prostate Formula, Fiber Max, maxi Cleanse, Enzyme Therapy, Chinese Garlic, Natures Healer, Silver, Magnesium, Germanium

Vegetable Juice Concentrates:

Spinach, tomato, parsley, mushroom, avocado

Support:

Prostate, colon. (Homeopathic Remedies: #4, #40, #835)

Testosterone

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

Testosterone stand alone indicators generally associated with:

Your score is ideal:

Generally associated with Low Testosterone:

Generally associated with High Testosterone:

Men Progesterone

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

0.32 - 0.52 0.10 - 0.84 Show Result

Men Progesterone stand alone indicators generally associated with:

Your score is ideal:

Generally associated with Low Men Progesterone:

Generally associated with High Men Progesterone:

Women Progesterone

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

0.32 - 0.52 0.10 - 0.84 Show Result

Women Progesterone stand alone indicators generally associated with:

Your score is ideal:

Generally associated with Low Women Progesterone:

Generally associated with High Progesterone women:

Fibrinogen

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

200 - 300 200 - 400 Show Result

Fibrinogen stand alone indicators generally associated with:

Inflammatory marking, early cardio-vascular disease and/or stroke warning, early Alzheimer’s warning

Your score is ideal:

Generally associated with Low Fibrinogen:

Multiple nutritional deficiencies syndrome, liver sluggishness, mal-absorption syndrome, efficiency in enzymes, junk food habit, excess sugar, hypochlorhydria, spontaneous bleeding, early heart disease warning, excess aspirin, blood thinners, medication

Corresponding need for nutritional support for Low Fibrinogen:

Beta Carotene, Mega B Complex 1000, Stress & Toxin Protector, Duo C Complex, 57 Super Minerals, Vitamin D-3 Complex, Green Drink, Jug One Protocol

Generally associated with High Fibrinogen:

Excess blood sledging, unexplained excess body fat weight gain, underlying inflammation, leaky gut, intestinal bacterial over growth, bowel toxicity, slow food transition, acute infection, premature aging, under performing pituitary, human growth hormone deficiency, trauma, tissue damage, body/mind physiological stress indicator, heart disease, stroke, Alzheimer’s early warning

Corresponding need for nutritional support for High Fibrinogen:

L-Carnitine, L-Arginine, I-Thyroid, Co-Enzyme Q-10, Super Oil, Borage Oil, Vitamin E Complex, Alpha Lipoic Acid, Duo C Complex, Yogurt Health Drink, Mega B Complex 1000, Stress & Toxin Protector

Vegetable Juice Concentrates:

Celery, zucchini, tomato, mushroom, peas

Support:

Gut. (Homeopathic Remedies: #7, #8)

Carcino Antigen – (CA-125)

Ideal

Preventive Medicine Range

Orthodox Medicine Range

Your test Score

0 - 10 0 - 20 Show Result

CA-125 stand alone indicators generally associated with:

Pre-ovarian cancer screening, early stage immune competency

Your score is ideal:

Generally associated with LowCA-125:

Low is desirable. Zero is ideal

Generally associated with High CA-125:

Cancer cells beginning to over run the immune system, pre-ovarian tumor warning, highly toxic condition neutralizing the body’s ability to contain and destroy all the cancer cells

Corresponding need for nutritional support for High CA-125:

Intensive naturopathic detoxification and nutritional saturation therapy is indicated

Vegetable Juice Concentrates:

Peas, celery, tomato, mushroom, garlic

Support:

Immune system. (Homeopathic Remedies: #4, #20, #807)

",16343,True,4637.658679414133,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; /** * This method will be called when we see '/*' and try to match it as a bracketed comment. * If the next character is '+', it should be parsed as hint later, and we cannot match * it as a bracketed comment. * * Returns true if the next character is '+'. */ public boolean isHint() { int nextChar = _input.LA(1); if (nextChar == '+') { return true; } else { return false; } } } singleStatement : statement ';'* EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE namespace (IF NOT EXISTS)? multipartIdentifier (commentSpec | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER namespace multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER namespace multipartIdentifier SET locationSpec #setNamespaceLocation | DROP namespace (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (commentSpec | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier alterColumnAction? #alterTableAlterColumn | ALTER TABLE table=multipartIdentifier partitionSpec? CHANGE COLUMN? colName=multipartIdentifier colType colPosition? #hiveChangeColumn | ALTER TABLE table=multipartIdentifier partitionSpec? REPLACE COLUMNS '(' columns=qualifiedColTypeWithPositionList ')' #hiveReplaceColumns | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? (commentSpec | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) ns=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) ns=multipartIdentifier)? #showColumns | SHOW VIEWS ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showViews | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier (AS SERDE)? #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) namespace EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeRelation | (DESC | DESCRIBE) QUERY? query #describeQuery | COMMENT ON namespace multipartIdentifier IS comment=(STRING | NULL) #commentNamespace | COMMENT ON TABLE multipartIdentifier IS comment=(STRING | NULL) #commentTable | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier (STRING | .*?) #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; commentSpec : COMMENT STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; namespace : NAMESPACE | DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; createTableClauses :((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | commentSpec | (TBLPROPERTIES tableProps=tablePropertyList))* ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier commentSpec? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=RLIKE pattern=valueExpression | NOT? kind=LIKE quantifier=(ANY | SOME | ALL) ('('')' | '(' expression (',' expression)* ')') | NOT? kind=LIKE pattern=valueExpression (ESCAPE escapeChar=STRING)? | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | FIRST '(' expression (IGNORE NULLS)? ')' #first | LAST '(' expression (IGNORE NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (FILTER '(' WHERE where=booleanExpression ')')? (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | HOUR | MINUTE | MONTH | SECOND | YEAR | identifier ; colPosition : position=FIRST | position=AFTER afterCol=errorCapturingIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (NOT NULL)? commentSpec? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (NOT NULL)? commentSpec? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (NOT NULL)? commentSpec? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | FILTER | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; alterColumnAction : TYPE dataType | commentSpec | colPosition | setOrDrop=(SET | DROP) NOT NULL ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `EXPLAIN SELECT ...` is a command, but EXPLAIN // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved //--ANSI-NON-RESERVED-START : ADD | AFTER | ALTER | ANALYZE | ANTI | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SEMI | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETMINUS | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | VIEWS | WINDOW //--ANSI-NON-RESERVED-END ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPE | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FILTER | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MINUTE | MONTH | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | VIEWS | WHEN | WHERE | WINDOW | WITH | YEAR ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ //--SPARK-KEYWORD-LIST-START ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILTER: 'FILTER'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; VIEWS: 'VIEWS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; //--SPARK-KEYWORD-LIST-END //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ('\\\\\\n' | ~[\\r\\n])* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' {!isHint()}? (BRACKETED_COMMENT|.)*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12541,False,2342.4853188219117,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, ANSI SQL parsing mode is enabled. */ public boolean ansi = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; singleInterval : INTERVAL? (intervalValue intervalUnit)+ EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER database db=errorCapturingIdentifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | ALTER database db=errorCapturingIdentifier SET locationSpec #setDatabaseLocation | DROP database (IF EXISTS)? db=errorCapturingIdentifier (RESTRICT | CASCADE)? #dropDatabase | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE multipartIdentifier RENAME COLUMN from=qualifiedName TO to=identifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=qualifiedNameList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=qualifiedNameList #dropTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE multipartIdentifier (ALTER | CHANGE) COLUMN? qualifiedName (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE tableIdentifier partitionSpec? CHANGE COLUMN? colName=errorCapturingIdentifier colType colPosition? #changeColumn | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER TABLE tableIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER VIEW tableIdentifier ADD (IF NOT EXISTS)? partitionSpec+ #addTablePartition | ALTER TABLE tableIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER TABLE tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER VIEW tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* #dropTablePartitions | ALTER TABLE multipartIdentifier SET locationSpec #setTableLocation | ALTER TABLE tableIdentifier partitionSpec SET locationSpec #setPartitionLocation | ALTER TABLE tableIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW tableIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? qualifiedName AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? qualifiedName #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=errorCapturingIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) tableIdentifier ((FROM | IN) db=errorCapturingIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (qualifiedName | pattern=STRING))? #showFunctions | SHOW CREATE TABLE tableIdentifier #showCreateTable | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) database EXTENDED? db=errorCapturingIdentifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE tableIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING qualifiedName ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assign (',' assign)* ; assign : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | IDENTIFIER '->' expression #lambda | '(' IDENTIFIER (',' IDENTIFIER)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : {ansi}? INTERVAL? intervalField+ | {!ansi}? INTERVAL intervalField* ; intervalField : value=intervalValue unit=intervalUnit (TO to=intervalUnit)? ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER qualifiedName ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=qualifiedName dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!ansi}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {ansi}? ansiNonReserved #unquotedIdentifier | {!ansi}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `spark.sql.ansi.enabled=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `spark.sql.ansi.enabled=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `spark.sql.ansi.enabled=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12081,False,2258.3283483992695,median "1 1 1 1 63 1 1 1 1 64 1 1 2 0 65 66 1 1 2 0 67 68 1 1 2 0 69 70 1 1 2 0 71 72 1 1 2 0 66 65 1 1 2 0 68 67 1 1 2 0 70 69 1 1 2 0 72 71 1 81 1 1 66 1 82 1 1 65 1 83 1 1 68 1 84 1 1 67 1 85 1 1 70 1 86 1 1 69 1 87 1 1 72 1 88 1 1 71 1 89 1 1 66 1 90 1 1 68 1 91 1 1 67 1 92 1 1 69 1 93 2 1 68 81 1 94 1 0 81 1 95 2 1 70 82 1 96 2 1 72 82 1 97 2 1 66 83 1 98 1 0 83 1 99 1 0 84 1 100 2 1 69 84 1 101 2 1 72 85 1 102 2 1 65 85 1 103 1 0 86 1 104 2 1 67 86 1 105 2 1 70 87 1 106 2 1 65 87 1 107 2 1 65 89 1 108 2 1 67 90 1 109 2 1 68 91 1 110 2 1 70 92 1 81 2 1 68 93 1 111 2 1 67 93 1 81 1 0 94 1 82 2 1 70 95 1 111 2 1 69 95 1 82 2 1 72 96 1 112 2 1 71 96 1 83 2 1 66 97 1 113 2 1 65 97 1 83 1 0 98 1 84 1 0 99 1 113 2 1 70 100 1 84 2 1 69 100 1 85 2 1 72 101 1 114 2 1 71 101 1 115 2 1 66 102 1 85 2 1 65 102 1 86 1 0 103 1 115 2 1 68 104 1 86 2 1 67 104 1 87 2 1 70 105 1 116 2 1 69 105 1 117 2 1 66 106 1 87 2 1 65 106 1 118 2 1 70 107 1 119 2 1 72 107 1 89 2 1 65 107 1 120 1 0 108 1 90 2 1 67 108 1 118 2 1 69 108 1 121 2 1 66 109 1 91 2 1 68 109 1 122 1 0 109 1 92 2 1 70 110 1 123 2 1 72 110 1 121 2 1 65 110 1 124 1 0 111 1 93 2 1 67 111 1 95 2 1 69 111 1 96 2 1 71 112 1 100 2 1 70 113 1 125 2 1 72 113 1 97 2 1 65 113 1 101 2 1 71 114 1 102 2 1 66 115 1 104 2 1 68 115 1 126 1 0 115 1 127 1 0 116 1 128 2 1 67 116 1 105 2 1 69 116 1 106 2 1 66 117 1 128 2 1 68 117 1 129 1 0 117 1 107 2 1 70 118 1 108 2 1 69 118 1 107 2 1 72 119 1 130 2 1 71 119 1 108 1 0 120 1 109 2 1 66 121 1 110 2 1 65 121 1 109 1 0 122 1 110 2 1 72 123 1 131 2 1 71 123 1 111 1 0 124 1 113 2 1 72 125 1 132 2 1 71 125 1 115 1 0 126 1 116 1 0 127 1 117 2 1 68 128 1 116 2 1 67 128 1 117 1 0 129 1 119 2 1 71 130 1 123 2 1 71 131 1 125 2 1 71 132 1 139 1 1 120 1 140 1 1 122 1 141 1 1 94 1 142 1 1 124 1 143 1 1 98 1 144 1 1 99 1 145 1 1 126 1 146 1 1 103 1 147 1 1 129 1 148 1 1 127 1 149 2 1 108 139 1 150 2 1 109 140 1 151 2 1 81 141 1 152 2 1 111 142 1 153 2 1 83 143 1 154 2 1 84 144 1 155 2 1 115 145 1 156 2 1 86 146 1 157 2 1 117 147 1 158 2 1 116 148 1 139 2 1 120 149 1 159 2 1 90 149 1 160 2 1 118 149 1 161 2 1 121 150 1 162 2 1 91 150 1 140 2 1 122 150 1 163 2 1 93 151 1 141 2 1 94 151 1 142 2 1 124 152 1 163 2 1 93 152 1 164 2 1 95 152 1 165 2 1 97 153 1 143 2 1 98 153 1 144 2 1 99 154 1 166 2 1 100 154 1 167 2 1 102 155 1 168 2 1 104 155 1 145 2 1 126 155 1 146 2 1 103 156 1 168 2 1 104 156 1 169 2 1 106 157 1 170 2 1 128 157 1 147 2 1 129 157 1 148 2 1 127 158 1 170 2 1 128 158 1 171 2 1 105 158 1 149 2 1 108 159 1 172 2 1 107 160 1 149 2 1 108 160 1 150 2 1 109 161 1 173 2 1 110 161 1 150 2 1 109 162 1 151 2 1 81 163 1 152 2 1 111 163 1 174 2 1 82 164 1 152 2 1 111 164 1 153 2 1 83 165 1 175 2 1 113 165 1 175 2 1 113 166 1 154 2 1 84 166 1 155 2 1 115 167 1 176 2 1 85 167 1 155 2 1 115 168 1 156 2 1 86 168 1 157 2 1 117 169 1 177 2 1 87 169 1 157 2 1 117 170 1 158 2 1 116 170 1 177 2 1 87 171 1 158 2 1 116 171 1 160 2 1 118 172 1 178 2 1 119 172 1 179 2 1 89 172 1 180 2 1 92 173 1 181 2 1 123 173 1 161 2 1 121 173 1 164 2 1 95 174 1 182 2 1 96 174 1 166 2 1 100 175 1 183 2 1 125 175 1 165 2 1 97 175 1 184 2 1 101 176 1 167 2 1 102 176 1 171 2 1 105 177 1 169 2 1 106 177 1 172 2 1 107 178 1 185 2 1 130 178 1 172 2 1 107 179 1 173 2 1 110 180 1 173 2 1 110 181 1 186 2 1 131 181 1 174 2 1 82 182 1 187 2 1 112 182 1 175 2 1 113 183 1 188 2 1 132 183 1 176 2 1 85 184 1 189 2 1 114 184 1 178 2 1 119 185 1 181 2 1 123 186 1 182 2 1 96 187 1 183 2 1 125 188 1 184 2 1 101 189 1 190 2 1 141 140 1 191 2 1 143 140 1 192 2 1 145 140 1 193 2 1 147 140 1 194 2 1 145 141 1 195 2 1 147 141 1 196 2 1 143 141 1 197 2 1 145 143 1 198 2 1 147 143 1 199 2 1 147 145 1 200 2 1 142 139 1 201 2 1 144 139 1 202 2 1 146 139 1 203 2 1 148 139 1 204 1 0 139 1 205 2 1 146 142 1 206 2 1 148 142 1 207 2 1 144 142 1 208 2 1 146 144 1 209 2 1 148 144 1 210 2 1 148 146 1 211 1 0 161 1 212 2 1 165 161 1 213 2 1 167 161 1 214 2 1 169 161 1 215 2 1 167 165 1 216 2 1 169 165 1 217 2 1 169 167 1 218 1 0 179 1 219 2 1 165 179 1 220 2 1 167 179 1 221 2 1 169 179 1 222 2 1 161 179 1 223 2 1 163 159 1 224 1 0 159 1 225 2 1 168 159 1 226 2 1 170 159 1 227 2 1 162 159 1 228 2 1 163 162 1 229 1 0 162 1 230 2 1 168 162 1 231 2 1 170 162 1 232 2 1 168 163 1 233 2 1 170 163 1 234 1 0 163 1 235 2 1 170 168 1 236 2 1 164 160 1 237 2 1 166 160 1 238 1 0 160 1 239 2 1 171 160 1 240 2 1 180 160 1 241 1 0 164 1 242 2 1 171 164 1 243 2 1 166 164 1 244 1 0 166 1 245 2 1 171 166 1 246 2 1 164 180 1 247 2 1 166 180 1 248 1 0 180 1 249 2 1 171 180 1 250 2 1 182 178 1 251 2 1 183 178 1 252 2 1 184 178 1 253 1 0 178 1 254 2 1 181 178 1 255 2 1 182 181 1 256 2 1 183 181 1 257 2 1 184 181 1 258 1 0 181 1 259 2 1 184 182 1 260 1 0 182 1 261 2 1 183 182 1 262 2 1 184 183 1 263 1 0 183 1 264 1 0 184 1 265 1 0 140 1 266 1 0 141 1 267 2 1 140 141 1 268 1 0 143 1 269 2 1 140 143 1 270 2 1 141 143 1 271 1 0 145 1 272 2 1 140 145 1 273 2 1 141 145 1 274 2 1 143 145 1 275 1 0 147 1 276 2 1 140 147 1 277 2 1 141 147 1 278 2 1 143 147 1 279 2 1 145 147 1 280 2 1 139 142 1 281 1 0 142 1 282 2 1 139 144 1 283 1 0 144 1 284 2 1 142 144 1 285 2 1 139 146 1 286 1 0 146 1 287 2 1 142 146 1 288 2 1 144 146 1 289 2 1 139 148 1 290 1 0 148 1 291 2 1 142 148 1 292 2 1 144 148 1 293 2 1 146 148 1 294 2 1 179 161 1 295 2 1 179 165 1 296 2 1 161 165 1 297 1 0 165 1 298 2 1 179 167 1 299 2 1 161 167 1 300 1 0 167 1 301 2 1 165 167 1 302 2 1 179 169 1 303 2 1 161 169 1 304 1 0 169 1 305 2 1 165 169 1 306 2 1 167 169 1 307 2 1 159 162 1 308 2 1 159 163 1 309 2 1 162 163 1 310 2 1 159 168 1 311 2 1 162 168 1 312 2 1 163 168 1 313 1 0 168 1 314 2 1 159 170 1 315 2 1 162 170 1 316 2 1 163 170 1 317 1 0 170 1 318 2 1 168 170 1 319 2 1 160 164 1 320 2 1 180 164 1 321 2 1 160 166 1 322 2 1 180 166 1 323 2 1 164 166 1 324 2 1 160 171 1 325 2 1 180 171 1 326 2 1 164 171 1 327 2 1 166 171 1 328 1 0 171 1 329 2 1 160 180 1 330 2 1 178 181 1 331 2 1 178 182 1 332 2 1 181 182 1 333 2 1 178 183 1 334 2 1 181 183 1 335 2 1 182 183 1 336 2 1 178 184 1 337 2 1 181 184 1 338 2 1 182 184 1 339 2 1 183 184 1 340 1 0 200 1 341 1 0 218 1 342 1 0 223 1 343 1 0 236 1 344 1 0 250 5 345 627 10 5 340 341 342 343 344 266 280 308 319 331 65 155 129 78 200 57 65 129 78 200 1 346 1 1 345 1 347 1 0 346 1 348 1 0 190 1 349 1 0 211 1 350 1 0 228 1 351 1 0 246 1 352 1 0 255 5 353 619 10 5 348 349 350 351 352 267 281 309 320 332 57 155 129 78 200 57 65 129 78 200 1 354 1 1 353 1 355 1 0 354 1 356 1 0 201 1 357 1 0 219 1 358 1 0 224 1 359 1 0 237 1 360 1 0 251 5 361 627 10 5 356 357 358 359 360 268 282 295 321 333 65 155 129 78 200 57 65 155 78 200 1 362 1 1 361 1 347 1 0 362 1 363 1 0 191 1 364 1 0 212 1 365 1 0 229 1 366 1 0 247 1 367 1 0 256 5 368 619 10 5 363 364 365 366 367 269 283 296 322 334 57 155 129 78 200 57 65 155 78 200 1 369 1 1 368 1 355 1 0 369 1 370 1 0 202 1 371 1 0 220 1 372 1 0 225 1 373 1 0 238 1 374 1 0 252 5 375 627 10 5 370 371 372 373 374 271 285 298 310 336 65 155 129 78 200 57 65 155 129 200 1 376 1 1 375 1 347 1 0 376 1 377 1 0 192 1 378 1 0 213 1 379 1 0 230 1 380 1 0 248 1 381 1 0 257 5 382 619 10 5 377 378 379 380 381 272 286 299 311 337 57 155 129 78 200 57 65 155 129 200 1 383 1 1 382 1 355 1 0 383 1 384 1 0 194 1 385 1 0 205 1 386 1 0 232 1 387 1 0 241 1 388 1 0 259 5 389 529 10 5 384 385 386 387 388 273 287 300 312 338 57 65 129 78 200 57 65 155 129 200 1 390 1 1 389 1 391 1 0 390 1 392 1 0 197 1 393 1 0 208 1 394 1 0 215 1 395 1 0 244 1 396 1 0 262 5 397 555 10 5 392 393 394 395 396 274 288 301 313 339 57 65 155 78 200 57 65 155 129 200 1 398 1 1 397 1 399 1 0 398 1 400 1 0 203 1 401 1 0 221 1 402 1 0 226 1 403 1 0 239 1 404 1 0 253 5 405 627 10 5 400 401 402 403 404 275 289 302 314 324 65 155 129 78 200 57 65 155 129 78 1 406 1 1 405 1 347 1 0 406 1 407 1 0 193 1 408 1 0 214 1 409 1 0 231 1 410 1 0 249 1 411 1 0 258 5 412 619 10 5 407 408 409 410 411 276 290 303 315 325 57 155 129 78 200 57 65 155 129 78 1 413 1 1 412 1 355 1 0 413 1 414 1 0 195 1 415 1 0 206 1 416 1 0 233 1 417 1 0 242 1 418 1 0 260 5 419 529 10 5 414 415 416 417 418 277 291 304 316 326 57 65 129 78 200 57 65 155 129 78 1 420 1 1 419 1 391 1 0 420 1 421 1 0 198 1 422 1 0 209 1 423 1 0 216 1 424 1 0 245 1 425 1 0 263 5 426 555 10 5 421 422 423 424 425 278 292 305 317 327 57 65 155 78 200 57 65 155 129 78 1 427 1 1 426 1 399 1 0 427 1 428 1 0 204 1 429 1 0 222 1 430 1 0 227 1 431 1 0 240 1 432 1 0 254 5 433 627 10 5 428 429 430 431 432 265 294 307 329 330 65 155 129 78 200 57 155 129 78 200 1 434 1 1 433 1 347 1 0 434 1 435 1 0 196 1 436 1 0 207 1 437 1 0 234 1 438 1 0 243 1 439 1 0 261 5 440 529 10 5 435 436 437 438 439 270 284 297 323 335 57 65 129 78 200 57 65 155 78 200 1 441 1 1 440 1 391 1 0 441 1 442 1 0 199 1 443 1 0 210 1 444 1 0 217 1 445 1 0 235 1 446 1 0 264 5 447 606 10 5 442 443 444 445 446 279 293 306 318 328 57 65 155 129 200 57 65 155 129 78 1 448 1 1 447 1 449 1 0 448 1 391 1 1 347 1 391 1 1 355 1 399 1 1 347 1 399 1 1 355 1 449 1 1 347 1 449 1 1 355 1 449 1 1 391 1 449 1 1 399 1 450 1 1 347 1 450 1 1 355 1 450 1 1 391 1 450 1 1 399 1 355 1 1 347 1 399 1 1 391 1 450 1 1 449 1 451 2 1 355 140 1 451 2 1 391 141 1 451 2 1 399 143 1 451 2 1 449 145 1 451 2 1 450 147 1 452 2 1 347 139 1 452 2 1 391 142 1 452 2 1 399 144 1 452 2 1 449 146 1 452 2 1 450 148 1 453 2 1 355 161 1 453 2 1 399 165 1 453 2 1 449 167 1 453 2 1 450 169 1 453 2 1 347 179 1 454 2 1 347 159 1 454 2 1 355 162 1 454 2 1 391 163 1 454 2 1 449 168 1 454 2 1 450 170 1 455 2 1 347 160 1 455 2 1 391 164 1 455 2 1 399 166 1 455 2 1 450 171 1 455 2 1 355 180 1 456 2 1 347 178 1 456 2 1 355 181 1 456 2 1 391 182 1 456 2 1 399 183 1 456 2 1 449 184 3 10 63 64 66 68 70 72 65 67 69 71 0 0 2 457 10 0 4 63 64 66 68 70 72 65 67 69 71 2 458 10 0 5 63 64 66 68 70 72 65 67 69 71 1 459 2 1 458 457 1 1 1 1 459 0 10 pipe(1,2) 11 pipe(1,4) 12 pipe(2,3) 13 pipe(2,4) 14 pipe(3,4) 15 pipe(3,5) 22 swap(pipe(1,2),pipe(1,2)) 23 swap(pipe(1,4),pipe(1,4)) 24 swap(pipe(2,3),pipe(2,3)) 25 swap(pipe(2,4),pipe(2,4)) 26 swap(pipe(3,4),pipe(3,4)) 27 swap(pipe(3,5),pipe(3,5)) 28 swap(pipe(1,2),pipe(2,1)) 29 swap(pipe(1,4),pipe(4,1)) 30 swap(pipe(2,3),pipe(3,2)) 31 swap(pipe(2,4),pipe(4,2)) 32 swap(pipe(3,4),pipe(4,3)) 33 swap(pipe(3,5),pipe(5,3)) 34 symm_pipe(1,2) 35 symm_pipe(1,4) 36 symm_pipe(2,3) 37 symm_pipe(2,4) 38 symm_pipe(3,4) 39 symm_pipe(3,5) 40 symm_pipe(2,1) 41 symm_pipe(4,1) 42 symm_pipe(3,2) 43 symm_pipe(4,2) 44 symm_pipe(4,3) 45 symm_pipe(5,3) 46 less_ico(pipe(1,2),pipe(2,3)) 47 less_ico(pipe(1,4),pipe(2,3)) 48 less_ico(pipe(1,2),pipe(2,4)) 49 less_ico(pipe(1,4),pipe(2,4)) 50 less_ico(pipe(1,2),pipe(3,4)) 51 less_ico(pipe(1,4),pipe(3,4)) 52 less_ico(pipe(2,3),pipe(3,4)) 53 less_ico(pipe(2,4),pipe(3,4)) 54 less_ico(pipe(1,2),pipe(3,5)) 55 less_ico(pipe(1,4),pipe(3,5)) 56 less_ico(pipe(2,3),pipe(3,5)) 57 less_ico(pipe(2,4),pipe(3,5)) 58 less_ico(pipe(1,2),pipe(1,4)) 59 less_ico(pipe(2,3),pipe(2,4)) 60 less_ico(pipe(3,4),pipe(3,5)) 9 tank(1) 3 valves_per_pipe(1) 61 drop(2,1) 62 drop(4,1) 2 valves_number(4) 63 valve(1,2) 64 valve(1,4) 66 valve(2,3) 68 valve(2,4) 70 valve(3,4) 72 valve(3,5) 65 valve(3,2) 67 valve(4,2) 69 valve(4,3) 71 valve(5,3) 73 broken(pipe(1,2),pipe(1,2)) 74 broken(pipe(1,4),pipe(1,4)) 75 broken(pipe(2,3),pipe(2,3)) 76 broken(pipe(2,4),pipe(2,4)) 77 broken(pipe(3,4),pipe(3,4)) 78 broken(pipe(3,5),pipe(3,5)) 89 broken(pipe(1,2),pipe(2,3)) 90 broken(pipe(1,2),pipe(2,4)) 91 broken(pipe(1,4),pipe(2,4)) 92 broken(pipe(1,4),pipe(3,4)) 93 broken(pipe(2,3),pipe(2,4)) 94 broken(pipe(2,3),pipe(1,2)) 95 broken(pipe(2,3),pipe(3,4)) 96 broken(pipe(2,3),pipe(3,5)) 97 broken(pipe(2,4),pipe(2,3)) 98 broken(pipe(2,4),pipe(1,2)) 99 broken(pipe(2,4),pipe(1,4)) 100 broken(pipe(2,4),pipe(3,4)) 101 broken(pipe(3,4),pipe(3,5)) 102 broken(pipe(3,4),pipe(2,3)) 103 broken(pipe(3,4),pipe(1,4)) 104 broken(pipe(3,4),pipe(2,4)) 105 broken(pipe(3,5),pipe(3,4)) 106 broken(pipe(3,5),pipe(2,3)) 118 broken(pipe(1,2),pipe(3,4)) 119 broken(pipe(1,2),pipe(3,5)) 120 broken(pipe(1,2),pipe(1,4)) 121 broken(pipe(1,4),pipe(2,3)) 122 broken(pipe(1,4),pipe(1,2)) 123 broken(pipe(1,4),pipe(3,5)) 124 broken(pipe(2,3),pipe(1,4)) 125 broken(pipe(2,4),pipe(3,5)) 126 broken(pipe(3,4),pipe(1,2)) 127 broken(pipe(3,5),pipe(1,4)) 128 broken(pipe(3,5),pipe(2,4)) 129 broken(pipe(3,5),pipe(1,2)) 79 extend(pipe(1,2),2) 80 extend(pipe(1,4),4) 81 extend(pipe(2,3),2) 82 extend(pipe(2,3),3) 83 extend(pipe(2,4),2) 84 extend(pipe(2,4),4) 85 extend(pipe(3,4),3) 86 extend(pipe(3,4),4) 87 extend(pipe(3,5),3) 88 extend(pipe(3,5),5) 107 extend(pipe(1,2),3) 108 extend(pipe(1,2),4) 109 extend(pipe(1,4),2) 110 extend(pipe(1,4),3) 111 extend(pipe(2,3),4) 112 extend(pipe(2,3),5) 113 extend(pipe(2,4),3) 114 extend(pipe(3,4),5) 115 extend(pipe(3,4),2) 116 extend(pipe(3,5),4) 117 extend(pipe(3,5),2) 130 extend(pipe(1,2),5) 131 extend(pipe(1,4),5) 132 extend(pipe(2,4),5) 133 reached(pipe(1,2),1) 134 reached(pipe(1,4),1) 135 reached(pipe(2,3),1) 136 reached(pipe(2,4),1) 137 reached(pipe(3,4),1) 138 reached(pipe(3,5),1) 149 reached(pipe(1,2),4) 150 reached(pipe(1,4),2) 151 reached(pipe(2,3),2) 152 reached(pipe(2,3),4) 153 reached(pipe(2,4),2) 154 reached(pipe(2,4),4) 155 reached(pipe(3,4),2) 156 reached(pipe(3,4),4) 157 reached(pipe(3,5),2) 158 reached(pipe(3,5),4) 172 reached(pipe(1,2),3) 173 reached(pipe(1,4),3) 174 reached(pipe(2,3),3) 175 reached(pipe(2,4),3) 176 reached(pipe(3,4),3) 177 reached(pipe(3,5),3) 185 reached(pipe(1,2),5) 186 reached(pipe(1,4),5) 187 reached(pipe(2,3),5) 188 reached(pipe(2,4),5) 189 reached(pipe(3,4),5) 139 deliver(pipe(1,2),pipe(1,4)) 140 deliver(pipe(1,4),pipe(1,2)) 141 deliver(pipe(2,3),pipe(1,2)) 142 deliver(pipe(2,3),pipe(1,4)) 143 deliver(pipe(2,4),pipe(1,2)) 144 deliver(pipe(2,4),pipe(1,4)) 145 deliver(pipe(3,4),pipe(1,2)) 146 deliver(pipe(3,4),pipe(1,4)) 147 deliver(pipe(3,5),pipe(1,2)) 148 deliver(pipe(3,5),pipe(1,4)) 159 deliver(pipe(1,2),pipe(2,4)) 160 deliver(pipe(1,2),pipe(3,4)) 161 deliver(pipe(1,4),pipe(2,3)) 162 deliver(pipe(1,4),pipe(2,4)) 163 deliver(pipe(2,3),pipe(2,4)) 164 deliver(pipe(2,3),pipe(3,4)) 165 deliver(pipe(2,4),pipe(2,3)) 166 deliver(pipe(2,4),pipe(3,4)) 167 deliver(pipe(3,4),pipe(2,3)) 168 deliver(pipe(3,4),pipe(2,4)) 169 deliver(pipe(3,5),pipe(2,3)) 170 deliver(pipe(3,5),pipe(2,4)) 171 deliver(pipe(3,5),pipe(3,4)) 178 deliver(pipe(1,2),pipe(3,5)) 179 deliver(pipe(1,2),pipe(2,3)) 180 deliver(pipe(1,4),pipe(3,4)) 181 deliver(pipe(1,4),pipe(3,5)) 182 deliver(pipe(2,3),pipe(3,5)) 183 deliver(pipe(2,4),pipe(3,5)) 184 deliver(pipe(3,4),pipe(3,5)) 16 dem(1,2,57) 17 dem(1,4,65) 18 dem(2,3,155) 19 dem(2,4,129) 20 dem(3,4,78) 21 dem(3,5,200) 190 compare(pipe(1,4),pipe(2,3),pipe(1,2),-57) 191 compare(pipe(1,4),pipe(2,4),pipe(1,2),-57) 192 compare(pipe(1,4),pipe(3,4),pipe(1,2),-57) 193 compare(pipe(1,4),pipe(3,5),pipe(1,2),-57) 194 compare(pipe(2,3),pipe(3,4),pipe(1,2),-57) 195 compare(pipe(2,3),pipe(3,5),pipe(1,2),-57) 196 compare(pipe(2,3),pipe(2,4),pipe(1,2),-57) 197 compare(pipe(2,4),pipe(3,4),pipe(1,2),-57) 198 compare(pipe(2,4),pipe(3,5),pipe(1,2),-57) 199 compare(pipe(3,4),pipe(3,5),pipe(1,2),-57) 200 compare(pipe(1,2),pipe(2,3),pipe(1,4),-65) 201 compare(pipe(1,2),pipe(2,4),pipe(1,4),-65) 202 compare(pipe(1,2),pipe(3,4),pipe(1,4),-65) 203 compare(pipe(1,2),pipe(3,5),pipe(1,4),-65) 204 compare(pipe(1,2),pipe(1,4),pipe(1,4),-65) 205 compare(pipe(2,3),pipe(3,4),pipe(1,4),-65) 206 compare(pipe(2,3),pipe(3,5),pipe(1,4),-65) 207 compare(pipe(2,3),pipe(2,4),pipe(1,4),-65) 208 compare(pipe(2,4),pipe(3,4),pipe(1,4),-65) 209 compare(pipe(2,4),pipe(3,5),pipe(1,4),-65) 210 compare(pipe(3,4),pipe(3,5),pipe(1,4),-65) 211 compare(pipe(1,4),pipe(2,3),pipe(2,3),-155) 212 compare(pipe(1,4),pipe(2,4),pipe(2,3),-155) 213 compare(pipe(1,4),pipe(3,4),pipe(2,3),-155) 214 compare(pipe(1,4),pipe(3,5),pipe(2,3),-155) 215 compare(pipe(2,4),pipe(3,4),pipe(2,3),-155) 216 compare(pipe(2,4),pipe(3,5),pipe(2,3),-155) 217 compare(pipe(3,4),pipe(3,5),pipe(2,3),-155) 218 compare(pipe(1,2),pipe(2,3),pipe(2,3),-155) 219 compare(pipe(1,2),pipe(2,4),pipe(2,3),-155) 220 compare(pipe(1,2),pipe(3,4),pipe(2,3),-155) 221 compare(pipe(1,2),pipe(3,5),pipe(2,3),-155) 222 compare(pipe(1,2),pipe(1,4),pipe(2,3),-155) 223 compare(pipe(1,2),pipe(2,3),pipe(2,4),-129) 224 compare(pipe(1,2),pipe(2,4),pipe(2,4),-129) 225 compare(pipe(1,2),pipe(3,4),pipe(2,4),-129) 226 compare(pipe(1,2),pipe(3,5),pipe(2,4),-129) 227 compare(pipe(1,2),pipe(1,4),pipe(2,4),-129) 228 compare(pipe(1,4),pipe(2,3),pipe(2,4),-129) 229 compare(pipe(1,4),pipe(2,4),pipe(2,4),-129) 230 compare(pipe(1,4),pipe(3,4),pipe(2,4),-129) 231 compare(pipe(1,4),pipe(3,5),pipe(2,4),-129) 232 compare(pipe(2,3),pipe(3,4),pipe(2,4),-129) 233 compare(pipe(2,3),pipe(3,5),pipe(2,4),-129) 234 compare(pipe(2,3),pipe(2,4),pipe(2,4),-129) 235 compare(pipe(3,4),pipe(3,5),pipe(2,4),-129) 236 compare(pipe(1,2),pipe(2,3),pipe(3,4),-78) 237 compare(pipe(1,2),pipe(2,4),pipe(3,4),-78) 238 compare(pipe(1,2),pipe(3,4),pipe(3,4),-78) 239 compare(pipe(1,2),pipe(3,5),pipe(3,4),-78) 240 compare(pipe(1,2),pipe(1,4),pipe(3,4),-78) 241 compare(pipe(2,3),pipe(3,4),pipe(3,4),-78) 242 compare(pipe(2,3),pipe(3,5),pipe(3,4),-78) 243 compare(pipe(2,3),pipe(2,4),pipe(3,4),-78) 244 compare(pipe(2,4),pipe(3,4),pipe(3,4),-78) 245 compare(pipe(2,4),pipe(3,5),pipe(3,4),-78) 246 compare(pipe(1,4),pipe(2,3),pipe(3,4),-78) 247 compare(pipe(1,4),pipe(2,4),pipe(3,4),-78) 248 compare(pipe(1,4),pipe(3,4),pipe(3,4),-78) 249 compare(pipe(1,4),pipe(3,5),pipe(3,4),-78) 250 compare(pipe(1,2),pipe(2,3),pipe(3,5),-200) 251 compare(pipe(1,2),pipe(2,4),pipe(3,5),-200) 252 compare(pipe(1,2),pipe(3,4),pipe(3,5),-200) 253 compare(pipe(1,2),pipe(3,5),pipe(3,5),-200) 254 compare(pipe(1,2),pipe(1,4),pipe(3,5),-200) 255 compare(pipe(1,4),pipe(2,3),pipe(3,5),-200) 256 compare(pipe(1,4),pipe(2,4),pipe(3,5),-200) 257 compare(pipe(1,4),pipe(3,4),pipe(3,5),-200) 258 compare(pipe(1,4),pipe(3,5),pipe(3,5),-200) 259 compare(pipe(2,3),pipe(3,4),pipe(3,5),-200) 260 compare(pipe(2,3),pipe(3,5),pipe(3,5),-200) 261 compare(pipe(2,3),pipe(2,4),pipe(3,5),-200) 262 compare(pipe(2,4),pipe(3,4),pipe(3,5),-200) 263 compare(pipe(2,4),pipe(3,5),pipe(3,5),-200) 264 compare(pipe(3,4),pipe(3,5),pipe(3,5),-200) 265 compare(pipe(1,2),pipe(1,4),pipe(1,2),57) 266 compare(pipe(1,2),pipe(2,3),pipe(1,2),57) 267 compare(pipe(1,4),pipe(2,3),pipe(1,2),57) 268 compare(pipe(1,2),pipe(2,4),pipe(1,2),57) 269 compare(pipe(1,4),pipe(2,4),pipe(1,2),57) 270 compare(pipe(2,3),pipe(2,4),pipe(1,2),57) 271 compare(pipe(1,2),pipe(3,4),pipe(1,2),57) 272 compare(pipe(1,4),pipe(3,4),pipe(1,2),57) 273 compare(pipe(2,3),pipe(3,4),pipe(1,2),57) 274 compare(pipe(2,4),pipe(3,4),pipe(1,2),57) 275 compare(pipe(1,2),pipe(3,5),pipe(1,2),57) 276 compare(pipe(1,4),pipe(3,5),pipe(1,2),57) 277 compare(pipe(2,3),pipe(3,5),pipe(1,2),57) 278 compare(pipe(2,4),pipe(3,5),pipe(1,2),57) 279 compare(pipe(3,4),pipe(3,5),pipe(1,2),57) 280 compare(pipe(1,2),pipe(2,3),pipe(1,4),65) 281 compare(pipe(1,4),pipe(2,3),pipe(1,4),65) 282 compare(pipe(1,2),pipe(2,4),pipe(1,4),65) 283 compare(pipe(1,4),pipe(2,4),pipe(1,4),65) 284 compare(pipe(2,3),pipe(2,4),pipe(1,4),65) 285 compare(pipe(1,2),pipe(3,4),pipe(1,4),65) 286 compare(pipe(1,4),pipe(3,4),pipe(1,4),65) 287 compare(pipe(2,3),pipe(3,4),pipe(1,4),65) 288 compare(pipe(2,4),pipe(3,4),pipe(1,4),65) 289 compare(pipe(1,2),pipe(3,5),pipe(1,4),65) 290 compare(pipe(1,4),pipe(3,5),pipe(1,4),65) 291 compare(pipe(2,3),pipe(3,5),pipe(1,4),65) 292 compare(pipe(2,4),pipe(3,5),pipe(1,4),65) 293 compare(pipe(3,4),pipe(3,5),pipe(1,4),65) 294 compare(pipe(1,2),pipe(1,4),pipe(2,3),155) 295 compare(pipe(1,2),pipe(2,4),pipe(2,3),155) 296 compare(pipe(1,4),pipe(2,4),pipe(2,3),155) 297 compare(pipe(2,3),pipe(2,4),pipe(2,3),155) 298 compare(pipe(1,2),pipe(3,4),pipe(2,3),155) 299 compare(pipe(1,4),pipe(3,4),pipe(2,3),155) 300 compare(pipe(2,3),pipe(3,4),pipe(2,3),155) 301 compare(pipe(2,4),pipe(3,4),pipe(2,3),155) 302 compare(pipe(1,2),pipe(3,5),pipe(2,3),155) 303 compare(pipe(1,4),pipe(3,5),pipe(2,3),155) 304 compare(pipe(2,3),pipe(3,5),pipe(2,3),155) 305 compare(pipe(2,4),pipe(3,5),pipe(2,3),155) 306 compare(pipe(3,4),pipe(3,5),pipe(2,3),155) 307 compare(pipe(1,2),pipe(1,4),pipe(2,4),129) 308 compare(pipe(1,2),pipe(2,3),pipe(2,4),129) 309 compare(pipe(1,4),pipe(2,3),pipe(2,4),129) 310 compare(pipe(1,2),pipe(3,4),pipe(2,4),129) 311 compare(pipe(1,4),pipe(3,4),pipe(2,4),129) 312 compare(pipe(2,3),pipe(3,4),pipe(2,4),129) 313 compare(pipe(2,4),pipe(3,4),pipe(2,4),129) 314 compare(pipe(1,2),pipe(3,5),pipe(2,4),129) 315 compare(pipe(1,4),pipe(3,5),pipe(2,4),129) 316 compare(pipe(2,3),pipe(3,5),pipe(2,4),129) 317 compare(pipe(2,4),pipe(3,5),pipe(2,4),129) 318 compare(pipe(3,4),pipe(3,5),pipe(2,4),129) 319 compare(pipe(1,2),pipe(2,3),pipe(3,4),78) 320 compare(pipe(1,4),pipe(2,3),pipe(3,4),78) 321 compare(pipe(1,2),pipe(2,4),pipe(3,4),78) 322 compare(pipe(1,4),pipe(2,4),pipe(3,4),78) 323 compare(pipe(2,3),pipe(2,4),pipe(3,4),78) 324 compare(pipe(1,2),pipe(3,5),pipe(3,4),78) 325 compare(pipe(1,4),pipe(3,5),pipe(3,4),78) 326 compare(pipe(2,3),pipe(3,5),pipe(3,4),78) 327 compare(pipe(2,4),pipe(3,5),pipe(3,4),78) 328 compare(pipe(3,4),pipe(3,5),pipe(3,4),78) 329 compare(pipe(1,2),pipe(1,4),pipe(3,4),78) 330 compare(pipe(1,2),pipe(1,4),pipe(3,5),200) 331 compare(pipe(1,2),pipe(2,3),pipe(3,5),200) 332 compare(pipe(1,4),pipe(2,3),pipe(3,5),200) 333 compare(pipe(1,2),pipe(2,4),pipe(3,5),200) 334 compare(pipe(1,4),pipe(2,4),pipe(3,5),200) 335 compare(pipe(2,3),pipe(2,4),pipe(3,5),200) 336 compare(pipe(1,2),pipe(3,4),pipe(3,5),200) 337 compare(pipe(1,4),pipe(3,4),pipe(3,5),200) 338 compare(pipe(2,3),pipe(3,4),pipe(3,5),200) 339 compare(pipe(2,4),pipe(3,4),pipe(3,5),200) 347 lower(pipe(1,2)) 355 lower(pipe(1,4)) 391 lower(pipe(2,3)) 399 lower(pipe(2,4)) 449 lower(pipe(3,4)) 450 lower(pipe(3,5)) 451 worst_deliv_dem(1,2,57) 452 worst_deliv_dem(1,4,65) 453 worst_deliv_dem(2,3,155) 454 worst_deliv_dem(2,4,129) 455 worst_deliv_dem(3,4,78) 456 worst_deliv_dem(3,5,200) 4 junction(1) 5 junction(2) 6 junction(3) 7 junction(4) 8 junction(5) 0 B+ 0 B- 1 0 1 ",16314,False,2406.106266548313,median "<%@ Control Language=""C#"" AutoEventWireup=""true"" CodeFile=""TemplateFilemanager.ascx.cs"" Inherits=""Modules_FileManager_FileMgr"" %>

Template File Manager

  • Add File
  • Delete File
  • Add Folder
  • Delete Folder
  • Copy
  • Move
  • Refresh
Add Fileclose
<%-- --%>
Browse Files:
Add New Folderclose
FolderName:
Type: Standard <%-- --%>
FileMgrPopUpclose

Edit Image

Download
X1 Y1 X2 Y2
W H
Download
Rename Fileclose
<%-- --%> <%-- --%>
File Name:
File Mode: Archive
Read
Write
Hidden
Message close

Add New Folderclose
Confirmationclose
",16383,True,2774.242887248273,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * When false, CREATE TABLE syntax without a provider will use * the value of spark.sql.sources.default as its provider. */ public boolean legacy_create_hive_table_by_default_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE namespace (IF NOT EXISTS)? multipartIdentifier (commentSpec | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER namespace multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER namespace multipartIdentifier SET locationSpec #setNamespaceLocation | DROP namespace (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | {!legacy_create_hive_table_by_default_enabled}? createTableHeader ('(' colTypeList ')')? tableProvider? createTableClauses (AS? query)? #createTable | {legacy_create_hive_table_by_default_enabled}? createTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (commentSpec | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier (TYPE dataType)? commentSpec? colPosition? #alterTableColumn | ALTER TABLE table=multipartIdentifier partitionSpec? CHANGE COLUMN? colName=multipartIdentifier colType colPosition? #hiveChangeColumn | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? (commentSpec | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) ns=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) ns=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) namespace EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | COMMENT ON namespace multipartIdentifier IS comment=(STRING | NULL) #commentNamespace | COMMENT ON TABLE multipartIdentifier IS comment=(STRING | NULL) #commentTable | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier (STRING | .*?) #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; commentSpec : COMMENT STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; namespace : NAMESPACE | DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; createTableClauses :((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | commentSpec | (TBLPROPERTIES tableProps=tablePropertyList))* ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier commentSpec? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=RLIKE pattern=valueExpression | NOT? kind=LIKE pattern=valueExpression (ESCAPE escapeChar=STRING)? | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (FILTER '(' WHERE where=booleanExpression ')')? (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | HOUR | MINUTE | MONTH | SECOND | YEAR | identifier ; colPosition : position=FIRST | position=AFTER afterCol=errorCapturingIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType commentSpec? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType commentSpec? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType commentSpec? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | FILTER | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `EXPLAIN SELECT ...` is a command, but EXPLAIN // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WINDOW ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPE | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FILTER | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MINUTE | MONTH | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WHEN | WHERE | WINDOW | WITH | YEAR ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILTER: 'FILTER'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12377,False,2323.424818912575,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; } singleStatement : statement ';' ; singleExpression : namedExpression EOF* ; singleTableIdentifier : tableIdentifier EOF* ; singleMultipartIdentifier : multipartIdentifier EOF* ; singleFunctionIdentifier : functionIdentifier EOF* ; singleDataType : dataType EOF* ; singleTableSchema : colTypeList EOF* ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE namespace (IF NOT EXISTS)? multipartIdentifier (commentSpec | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER namespace multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER namespace multipartIdentifier SET locationSpec #setNamespaceLocation | DROP namespace (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (commentSpec | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier alterColumnAction? #alterTableAlterColumn | ALTER TABLE table=multipartIdentifier partitionSpec? CHANGE COLUMN? colName=multipartIdentifier colType colPosition? #hiveChangeColumn | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? (commentSpec | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) ns=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) ns=multipartIdentifier)? #showColumns | SHOW VIEWS ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showViews | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier (AS SERDE)? #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) namespace EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeRelation | (DESC | DESCRIBE) QUERY? query #describeQuery | COMMENT ON namespace multipartIdentifier IS comment=(STRING | NULL) #commentNamespace | COMMENT ON TABLE multipartIdentifier IS comment=(STRING | NULL) #commentTable | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier (STRING | .*?) #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; commentSpec : COMMENT STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; namespace : NAMESPACE | DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; createTableClauses :((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | commentSpec | (TBLPROPERTIES tableProps=tablePropertyList))* ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier commentSpec? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=RLIKE pattern=valueExpression | NOT? kind=LIKE pattern=valueExpression (ESCAPE escapeChar=STRING)? | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | FIRST '(' expression (IGNORE NULLS)? ')' #first | LAST '(' expression (IGNORE NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (FILTER '(' WHERE where=booleanExpression ')')? (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | HOUR | MINUTE | MONTH | SECOND | YEAR | identifier ; colPosition : position=FIRST | position=AFTER afterCol=errorCapturingIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (NOT NULL)? commentSpec? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (NOT NULL)? commentSpec? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (NOT NULL)? commentSpec? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | FILTER | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; alterColumnAction : TYPE dataType | commentSpec | colPosition | setOrDrop=(SET | DROP) NOT NULL ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `EXPLAIN SELECT ...` is a command, but EXPLAIN // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | VIEWS | WINDOW ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPE | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FILTER | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MINUTE | MONTH | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | VIEWS | WHEN | WHERE | WINDOW | WITH | YEAR ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILTER: 'FILTER'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; VIEWS: 'VIEWS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ('\\\\\\n' | ~[\\r\\n])* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ;",12310,False,2307.7156330296543,median " ASP Tutorial
w3schools.com
THE WORLD'S LARGEST WEB DEVELOPER SITE
×

ASP Tutorials

ASP HOME

WP Tutorial

WebPages Intro WebPages Razor WebPages Layout WebPages Folders WebPages Global WebPages Forms WebPages Objects WebPages Files WebPages Databases WebPages Helpers WebPages WebGrid WebPages Charts WebPages Email WebPages Security WebPages Publish WebPages Examples WebPages Classes

ASP.NET Razor

Razor Intro Razor Syntax Razor C# Variables Razor C# Loops Razor C# Logic Razor VB Variables Razor VB Loops Razor VB Logic

ASP Classic

ASP Intro ASP Install ASP Syntax ASP Variables ASP Procedures ASP Conditionals ASP Looping ASP Forms ASP Cookies ASP Session ASP Application ASP #include ASP Global.asa ASP AJAX ASP e-mail ASP Examples

ASP Reference

ASP VB Functions ASP VB Keywords ASP Response ASP Request ASP Application ASP Session ASP Server ASP Error ASP FileSystem ASP TextStream ASP Drive ASP File ASP Folder ASP Dictionary ASP AdRotator ASP BrowserCap ASP Content Linking ASP Content Rotator ASP Quick Ref

ADO Tutorial

ADO Intro ADO Connect ADO Recordset ADO Display ADO Query ADO Sort ADO Add ADO Update ADO Delete ADO Demo ADO Speed Up

ADO Objects

ADO Command ADO Connection ADO Error ADO Field ADO Parameter ADO Property ADO Record ADO Recordset ADO Stream ADO DataTypes

ASP and ASP.NET Tutorials

ASP stands for Active Server Pages

ASP is a development framework for building web pages.

ASP supports many different development models:

  • Classic ASP
  • ASP.NET Web Forms
  • ASP.NET MVC
  • ASP.NET Web Pages
  • ASP.NET API
  • ASP.NET Core

The ASP Technology

ASP and ASP.NET are server side technologies.

Both technologies enable computer code to be executed by an Internet server.

When a browser requests an ASP or ASP.NET file, the ASP engine reads the file, executes any code in the file, and returns the result to the browser.


Classic ASP - Active Server Pages

ASP (aka Classic ASP) was introduced in 1998 as Microsoft's first server side scripting language.

Classic ASP pages have the file extension .asp and are normally written in VBScript.

Visit our Classic ASP Tutorial »

ASP.NET

ASP.NET was released in 2002 as a successor to Classic ASP.

ASP.NET pages have the extension .aspx and are normally written in C# (C sharp).

ASP.NET 4.6 is the latest official version of ASP.NET.

ASP.NET 5 was expected to be an important redesign of ASP.NET.

However, the development of ASP.NET 5 was stopped in favor of ASP.NET Core.



ASP.NET Web Pages

ASP.NET Web Pages is an SPA application model (Single Page Application).

The SPA model is quite similar to PHP and Classic ASP.

ASP.NET Web Pages is being merged into the new ASP.NET Core.

Visit our Web Pages Tutorial »

ASP.NET MVC

ASP.NET MVC is an MVC application model (Model-View-Controller).

ASP.NET MVC is being merged into the new ASP.NET Core.

ASP.NET MVC is not covered in this tutorial.


ASP.NET Web API

ASP.NET API is an API application model (Application Programming Interface).

ASP.NET API is being merged into the new ASP.NET Core.

ASP.NET API is not covered in this tutorial.


ASP.NET Web Forms

ASP.NET Web Forms is an event driven application model.

ASP.NET Web Forms is not a part of the new ASP.NET Core.

ASP.NET Web Forms is not covered in this tutorial.


ASP.NET Core

ASP.NET Core was released in 2016.

ASP.NET Core merges ASP.NET MVC, ASP.NET Web API, and ASP.NET Web Pages into one application framework.

ASP.NET Core is not covered in this tutorial.


SHARE






×

Your Suggestion:


×

Thank You For Helping Us!

Your message has been sent to W3Schools.


W3Schools is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2018 by Refsnes Data. All Rights Reserved.
Powered by W3.CSS.



",16161,False,2379.4828203287443,median "<%@ Page Language=""C#"" %> <%@ Import Namespace=""System.Globalization"" %> <%@ Import Namespace=""System.Security.Cryptography.X509Certificates"" %> WorldWide Telescope Web Client <% if (Client == Clients.Html5 || Client == Clients.Mobile) { string css = """"; css+=""""; css+=""""; %> <%=css%> <% if (Debug || DebugChrome) { %> <% } else { %> <% } %> <% } else if (Client == Clients.Silverlight) { %> <% } %> "" data-ng-app=""wwtApp"" data-res-location=""<%= ResourcesLocation%>"" data-version=""1"" data-res-version=""<%= ResourcesVersion%>"" data-liveId=""<%=ConfigurationManager.AppSettings[""LiveClientId""]%>"" data-standalone-mode=""<%=ConfigurationManager.AppSettings[""Standalone""]%>""> <% if (Client == Clients.Html5 || Client == Clients.Mobile) { %>
"">
"">
Enter Text
<% if (Client == Clients.Mobile) { %> "" data-ng-class=""searchModal ? 'hide':'btn share-button'"" data-placement=""bottom-left"" data-ng-hide=""showMobileTracking()"" > '"">

American Astronomical Society
WorldWide Telescope





Please ensure you have a strong connection to the internet for the best experience.

'"">
{{nboCount}}
 

<% } %> <%if (Client == Clients.Html5) { %> '""> '"" onload=""initFinder()"">
    {{bc}} > 
    '"">
    {{bc}} > 
    15 && $index >= currentPage * pageSize && $index < (currentPage+1) * pageSize""> 15 && !($index >= currentPage * pageSize && $index < (currentPage+1) * pageSize)"">
     
    '"">
    {{bc}} > 
    '"">
    <%-- Text intentionally left in elements so localization directive will keep the colon and no need to wrap an additional span inside. Directive will replace with regexp. --%>
    "" ng-controller=""ObservingTimeController"" data-animation=""am-flip-x"" data-placement=""bottom-right""> {{now | date:'yyyy/MM/dd HH:mm:ss'}}  

    <% if (Debug) { %>
    <% } %>
    {{redirectingSeconds}}

    <% if (ADS) {%>
     
      {{year}}
    <% } %>

    {{ !tour.minuteDuration ? '00' : tour.minuteDuration > 9 ? tour.minuteDuration : '0' + tour.minuteDuration}}:{{ !tour.secDuration ? '00' : tour.secDuration > 9 ? tour.secDuration : '0' + tour.secDuration}}
    "" trigger=""click"" placement=""bottom-left"" data-content=""{tour}"" data-container=""body"" id=""newTourProps"">
    "" trigger=""click"" placement=""bottom-left"" data-content=""{1}"" title=""Transition"" data-container=""body"" data-auto-close=""true"" data-on-show=""testfn()"" data-on-hide=""testfn()""> <%-- slew --%>
    <%-- xfade --%>
    <%-- xcut --%>
    <%-- fadeoutin --%>
    <%-- fadein --%>
    <%-- fadeout --%>
    '"">
    {{scrubber.title}}
    {{scrubber.right}}  {{scrubber.left}} 
    "" data-container=""body"" data-placement=""top-right"" >

    : {{formatted.RA}}

    : {{formatted.Dec}}

    : {{formatted.Lat}}

    : {{formatted.Lng}}

    {{formatted.Constellation}} {{formatted.Zoom}}

     
    '"">

    WorldWide Telescope

      '"">
    <% } %>
    <% } else if (Client == Clients.Silverlight) { %>
    ,tour=<% Page.Response.Output.Write(Request.Params[""tour""]); %>,webkey=<% Page.Response.Output.Write(ConfigurationManager.AppSettings[""webkey""]); %>"" />
    This page requires Silverlight 4.

    <% } %> ",16302,True,3009.6565428874305,median "<%-- // // DefaultWsdlHelpGenerator.aspx: // // Author: // Lluis Sanchez Gual (lluis@ximian.com) // // (C) 2003 Ximian, Inc. http://www.ximian.com // --%> <%@ Import Namespace=""System.Collections"" %> <%@ Import Namespace=""System.IO"" %> <%@ Import Namespace=""System.Xml.Serialization"" %> <%@ Import Namespace=""System.Xml"" %> <%@ Import Namespace=""System.Xml.Schema"" %> <%@ Import Namespace=""System.Web.Services.Description"" %> <%@ Import Namespace=""System"" %> <%@ Import Namespace=""System.Net"" %> <%@ Import Namespace=""System.Globalization"" %> <%@ Import Namespace=""System.Resources"" %> <%@ Import Namespace=""System.Diagnostics"" %> <%@ Import Namespace=""System.CodeDom"" %> <%@ Import Namespace=""System.CodeDom.Compiler"" %> <%@ Import Namespace=""Microsoft.CSharp"" %> <%@ Import Namespace=""Microsoft.VisualBasic"" %> <%@ Import Namespace=""System.Text"" %> <%@ Import Namespace=""System.Text.RegularExpressions"" %> <%@ Import Namespace=""System.Security.Cryptography.X509Certificates"" %> <%@ Assembly name=""System.Web.Services"" %> <%@ Page debug=""true"" %> ?disco""/> <%=WebServiceName%> Web Service
    Web Service
    <%=WebServiceName%>
    Overview
    Service Description
    Client proxy

    <%#FormatBindingName(DataBinder.Eval(Container.DataItem, ""Name"").ToString())%> ?<%=GetTabContext(""op"",null)%>op=<%#GetOpName(Container.DataItem)%>&bnd=<%#DataBinder.Eval(Container.DataItem, ""Binding.Name"")%>""><%#GetOpName(Container.DataItem)%>

    <% if (CurrentPage == ""main"") {%>

    Web Service Overview

    <%=WebServiceDescription%> <%} if (DefaultBinding == null) {%> This service does not contain any public web method. <%} else if (CurrentPage == ""op"") {%> <%=CurrentOperationName%>

    <% WriteTabs (); %>


    <% if (CurrentTab == ""main"") { %> Input Parameters
    <% if (InParams.Count == 0) { %> No input parameters
    <% } else { %>
    <%#DataBinder.Eval(Container.DataItem, ""Name"")%> <%#DataBinder.Eval(Container.DataItem, ""Type"")%>
    <% } %>
    <% if (OutParams.Count > 0) { %> Output Parameters
    <%#DataBinder.Eval(Container.DataItem, ""Name"")%> <%#DataBinder.Eval(Container.DataItem, ""Type"")%>

    <% } %> Remarks
    <%=OperationDocumentation%>

    Technical information
    Format: <%=CurrentOperationFormat%>
    Supported protocols: <%=CurrentOperationProtocols%> <% } %> <% if (CurrentTab == ""test"") { if (CurrentOperationSupportsTest) {%> Enter values for the parameters and click the 'Invoke' button to test this method:

    "" method=""GET""> ""> ""> ""> "">
    <%#DataBinder.Eval(Container.DataItem, ""Name"")%>:  "">
     
    ""> The web service returned the following result:

    <%=GetTestResult()%>
    <% } else {%> The test form is not available for this operation because it has parameters with a complex structure. <% } %> <% } %> <% if (CurrentTab == ""msg"") { %> The following are sample SOAP requests and responses for each protocol supported by this method:

    <% if (IsOperationSupported (""Soap"")) { %> Soap

    <%=GenerateOperationMessages (""Soap"", true)%>

    <%=GenerateOperationMessages (""Soap"", false)%>

    <% } %> <% if (IsOperationSupported (""HttpGet"")) { %> HTTP Get

    <%=GenerateOperationMessages (""HttpGet"", true)%>

    <%=GenerateOperationMessages (""HttpGet"", false)%>

    <% } %> <% if (IsOperationSupported (""HttpPost"")) { %> HTTP Post

    <%=GenerateOperationMessages (""HttpPost"", true)%>

    <%=GenerateOperationMessages (""HttpPost"", false)%>

    <% } %> <% } %> <%} else if (CurrentPage == ""proxy"") {%>
    "" name=""langForm"" method=""GET""> Select the language for which you want to generate a proxy "">    

    <%=CurrentProxytName%>    "">Download

    ""><%=GetProxyCode ()%>
    <%} else if (CurrentPage == ""wsdl"") {%> <% if (descriptions.Count > 1 || schemas.Count > 1) {%> The description of this web service is composed by several documents. Click on the document you want to see: <%} else {%> <%}%>
    <%=CurrentDocumentName%>    "">Download

    <%=GenerateDocument ()%>
    <%}%>














    ",16153,False,2495.4886775814584,median " SVG Examples
    w3schools.com
    THE WORLD'S LARGEST WEB DEVELOPER SITE

    SVG Examples


    Try-it Yourself Examples

    The examples below embed the SVG code directly into the HTML code.

    This is supported by Firefox, Internet Explorer 9, Google Chrome, Opera, and Safari.


    SVG Examples

    SVG Basic Shapes

    A circle
    A rectangle
    A rectangle with opacity
    A rectangle with opacity 2
    A rectangle with rounded corners
    An ellipse
    Three ellipses on top of each other
    Two ellipses
    A line
    A polygon with three sides
    A polygon with four sides
    A star
    Another star
    A polyline
    Another polyline
    A path
    A quadratic Bézier curve
    Write a text
    Rotate a text
    Text on several lines
    Text as a link
    Defines the color of a line, text or outline (stroke)
    Defines the width of a line, text or outline (stroke-width)
    Defines different types of endings to an open path (stroke-linecap)
    Defines dashed lines (stroke-dasharray)

    SVG Filters

    feGaussianBlur - blur effect
    feOffset - offset a rectangle, then blend the original on top of the offset image
    feOffset - blur the offset image
    feOffset - make the shadow black
    feOffset - treat the shadow as a color
    A feBlend filter
    Filter 1
    Filter 2
    Filter 3
    Filter 4
    Filter 5
    Filter 6

    SVG Gradients

    An ellipse with a horizontal linear gradient from yellow to red
    An ellipse with a vertical linear gradient from yellow to red
    An ellipse with a horizontal linear gradient from yellow to red, and a text
    An ellipse with a radial gradient from white to blue
    Another ellipse with a radial gradient from white to blue

    SVG Misc

    Rectangle that repeatedly fade away over 5 seconds
    A growing rectangle that will change color
    Three rectangles that will change color
    Move text along a motion path
    Move, rotate, and scale text along a motion path
    Move, rotate, and scale text along a motion path + a growing rectangle that will change color
    Rotating ellipses


    SHARE






    ×

    Your Suggestion:


    ×

    Thank You For Helping Us!

    Your message has been sent to W3Schools.


    W3Schools is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2018 by Refsnes Data. All Rights Reserved.
    Powered by W3.CSS.



    ",16189,False,2435.386234444747,median "<%@ Page Language=""vb"" AutoEventWireup=""false"" CodeBehind=""EmployeeManager.aspx.vb"" Inherits=""DiversifiedLogistics.EmployeeManager"" %> Employee Manager
    <%-- ******************* end Page Controls ******************* --%> <%-- ******************* end Left Side employee Grid **********************--%> ""> "">
    <%-- --%> <%-- --%>
    <%-- ******************* LEFT COLUMN ******************* --%> <%-- ******************* start Page Controls ******************* --%>
    <%-- ******************* end Left column ******************* --%> <%-- *******************Location Selector and help link at top of right side **********************--%>
    <%-- ******************* start RIGHT COLUMN ******************* --%>
    <%-- ******************************************************* --%> <%-- ******************* PAGE VIEW ONE ******************* --%> <%-- ******************************************************* --%>
    Comments
    Certifications  
    <%-- ******************* start Picture Comments Certifications **********************--%> <%-- ******************* end Right Side Access **********************--%>
    Employment    
    First Name
    Last Name
    <%-- ******************* start Employment Grid **********************--%> <%# Eval(""PayRateHourly"")%> <%# Eval(""PayRatePercentage"")%> <%-- ******************* Add Employment Button **********************--%>
    <%-- ******************* end Grid Commands Table **********************--%>
    <%-- ******************* end Employment Grid **********************--%> <%-- ******************* Start Add New Employment Form **********************--%>
    New Employment     <%-- ******************* start Row One **********************--%> <%-- ******************* start Left Column **********************--%> <%-- ******************* end Left Column **********************--%><%-- ******************* start Right Column **********************--%> <%-- ******************* end Right Column **********************--%> <%-- ******************* end Row One **********************--%> <%-- ******************* start Row Two **********************--%> <%-- ******************* end Row Two **********************--%>
    Job Title

    Start Date


    Primary Pay Type  
    <%-- --%>
    Pay Rate(s) <%-- --%>
    Hourly
    and/or Percent
    OR Other
    Add New Employment

    Job Title
    Select the employee's Job Title from the drop-down list.
    The one consideration here is 'Unloader Supervisor'.  An employee's Job Title MUST be set to 'Unloader Supervisor' if they are to be paid 'Supervisor Pay' in a pay period.   (see Start Date below)
     
    Primary Pay Type
    It is important that the Primary Pay Type be set correctly.
    Please see the help file for Primary Pay Type.
     
    Pay Rate(s)
    Hourly - Enter the hourly pay rate.
    Percentage - example: for 27 and ¼ percent enter  27.25
    Selecting the 'Percentage' pay type allows you to enter a Percentage rate AND and Hourly rate for those times when you need this employee to clock in 'by the hour'. (setting the isHourly checkbox when clocking in)
    Other - This will open the 'Other Pay' window.
     
    Start Date
    Select a start date from the calendar control
     
    To Close - Click X in upper right corner
    Primary Pay Type

    Important!
    It is important that the 'Primary Pay Type' be properly set.
    Some important payroll calculations will depend on this field.
    Hourly
    When this is set to 'Hourly' the employee shall be paid an hourly rate ONLY.
    An 'Hourly' employee will NEVER be paid for 'load business' and ALL clock-ins will be converted so that the Hourly field is always true (checked).  If you intend to pay this employee for any load business in current pay period then you MUST choose the 'Percentage' pay type.
    Percentage
    Choose this pay type if you intend to pay the employee a percentage of his/her
    load work.  This pay type will allow you to ALSO enter an hourly rate for those times when you need this employee to clock in 'by the hour'.
    (-- by checking the 'Hourly' box on the hand-held when clocking in --)
     
    To Close - Move your mouse away from this help screen
    Location
    Home Location:
    Current Location:
    Access  
    PIN* LoginID Password Payroll #
    <%-- *******************Access rtds **********************--%>
    RTDS Hand Held
       
    <%-- *******************Access seu.div-log **********************--%>
    SEU.Div-Log.com

    "" />
    Access section
    ** New Hire will only need enter PIN number in this section.
    PIN number
    Corporate recommends using the last 4 digits of the employee's Social Security #
    LoginID
    This number is auto-generated and cannot be changed.  The default number will generally be a location ident followed by the next sequential employee number.  For exceptions, contact the IT Department.
    Password
    Initially auto-generated in the format of their LoginID followed by the word 'welcome' in lowercase characters.  example: oc2345welcome
    Using their LoginID and this password the employee can log into the
    SEU.Div-Log.com website to view their hours, earnings and more.
    If the employee has changed the default password, you will see a 'Reset Password' link in place of the password.  Click the link IF you have need to reset the employee's password to the default new password.
    SEU.Div-Log.com ---
    Login Approved
    UN-check this box to prevent the employee from logging in to the web site.
    eMail Address
    A default NON-working eMail address is initially assigned to each employee.
    If the employee has another eMail address, enter it in the space provided.
    Employee Role
    Select the employee's current Role (or position) by selecting the appropriate check box(es).   This will determine the employee's access level on this web portal.
     
    To Close - Click X in upper right corner
    Employment

    When a new employee is hired and EACH time that the employee's job title, pay type and/or pay rate is changed, a NEW 'Employment' record is created and added to the grid.
     
    Employment Grid
    The employment grid displays the three most recent employment records with the most recent record on top.  IF there are more than three records, you will see a 'Show All' link in the bottom right corner of the grid.
    To change an employee's job title, pay type or pay rate, click the 'Change Employment' link below the grid.
     
    Change Employment
    Clicking this link will display a form to change or set a new Job Title, Primary Pay Type and Pay Rate(s) for this employee.  A new employment record will be created and will become effective on your selected 'Start Date'. (see form)
     
    To Close - Click X in upper right corner
    <%-- ******************************************************* --%> <%-- ******************* PAGE VIEW TWO ******************* --%> <%-- ******************************************************* --%>
    First Name
    Last Name
    Race

    SSN
    Address
    Home Phone
    Cell / Alt Phone
    Emergency Contact Info
    Online Documents

    future use

    <%--
    --%> <%-- ******************************************************* --%> <%-- ******************* PAGE VIEW PHOTO ID ******************* --%> <%-- ******************************************************* --%>






     future use
    <%-- ******************************************************* --%> <%-- ******************* PAGE VIEW Payroll ******************* --%> <%-- ******************************************************* --%>

    Accumulated Sick Leave:  hrs
    Hours Available:
    Authorize Sick Leave: (min  hrs)
    First Day Missed:
    Last Day Missed:
    Comments:



    Are you sure?
     "" ConfirmDialogType=""RadWindow"" ButtonType=""ImageButton"" CommandName=""Delete"" Text=""Delete"" UniqueName=""DeleteColumn"">
    <%-- ******************************************************* --%>
    <%-- ******************************************************* --%>


    <<<---- Select an Employee from left"" />





    <%-- ******************************************************* --%> <%-- ********************** TOOL TIPS ********************** --%> <%-- ******************************************************* --%> Employee Manager
    New Hire
    To add a new hire, click the New Hire link above the employee list next to location selector. (a location must be selected)  Also, the link will NOT be visible while an employee record is being displayed or edited.  If an employee record is open, you must click the 'Cancel / Close' button to make the link visible again.
    Employee Name
    To edit the employee's name, click on their name (the big blue characters).
    After making changes, click 'Save Changes' button.
    Comments
    Enter comments as you wish.  Click 'Save Changes' button.
    Certifications
    To help you in keeping them current, certification dates will appear in Black, then Orange, then Red as they approach expiration.  Click the edit link to manage the employee's certifications.  You DO NOT have to click the save button after editing certifications.
    Employment / Location
    Click the help link in the 'Employment' section.
    Access
    Click the help link in the 'Access' section.
    MugShot®
    PLEASE provide, as best possible, a nice ""Portrait"" style picture.   If you have any questions as to how to frame an employee MugShot® please study your driver license picture.  Close-up, neutral background, portrait orientation (camera / phone on it's side)  At the point we begin to issue ID Badges, we will use this image.  You DO NOT have to click the save button after uploading image.
     
    To Close - Click X in upper right corner
    "" SelectCommand=""SELECT JobTitle.JobTitleID, JobTitle.JobTitle FROM JobTitle INNER JOIN LocationJobTitle ON JobTitle.JobTitleID = LocationJobTitle.JobTitleID WHERE (LocationJobTitle.LocationID = @locaid) ORDER BY JobTitle"" > ",16276,True,2687.842985862645,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * When false, CREATE TABLE syntax without a provider will use * the value of spark.sql.sources.default as its provider. */ public boolean legacy_create_hive_table_by_default_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE namespace (IF NOT EXISTS)? multipartIdentifier (commentSpec | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER namespace multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER namespace multipartIdentifier SET locationSpec #setNamespaceLocation | ALTER namespace multipartIdentifier SET OWNER ownerType=(USER | ROLE | GROUP) identifier #setNamespaceOwner | DROP namespace (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | {!legacy_create_hive_table_by_default_enabled}? createTableHeader ('(' colTypeList ')')? tableProvider? createTableClauses (AS? query)? #createTable | {legacy_create_hive_table_by_default_enabled}? createTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (commentSpec | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier (TYPE dataType)? commentSpec? colPosition? #alterTableColumn | ALTER TABLE table=multipartIdentifier ALTER COLUMN? column=multipartIdentifier setOrDrop=(SET | DROP) NOT NULL #alterColumnNullability | ALTER TABLE table=multipartIdentifier partitionSpec? CHANGE COLUMN? colName=multipartIdentifier colType colPosition? #hiveChangeColumn | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? (commentSpec | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) ns=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) ns=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) namespace EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeRelation | (DESC | DESCRIBE) QUERY? query #describeQuery | COMMENT ON namespace multipartIdentifier IS comment=(STRING | NULL) #commentNamespace | COMMENT ON TABLE multipartIdentifier IS comment=(STRING | NULL) #commentTable | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier (STRING | .*?) #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; commentSpec : COMMENT STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; namespace : NAMESPACE | DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; createTableClauses :((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | commentSpec | (TBLPROPERTIES tableProps=tablePropertyList))* ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier commentSpec? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=RLIKE pattern=valueExpression | NOT? kind=LIKE pattern=valueExpression (ESCAPE escapeChar=STRING)? | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (FILTER '(' WHERE where=booleanExpression ')')? (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | HOUR | MINUTE | MONTH | SECOND | YEAR | identifier ; colPosition : position=FIRST | position=AFTER afterCol=errorCapturingIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (NOT NULL)? commentSpec? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (NOT NULL)? commentSpec? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (NOT NULL)? commentSpec? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | FILTER | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `EXPLAIN SELECT ...` is a command, but EXPLAIN // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | OWNER | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WINDOW ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPE | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FILTER | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MINUTE | MONTH | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | OWNER | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WHEN | WHERE | WINDOW | WITH | YEAR ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILTER: 'FILTER'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; OWNER: 'OWNER'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12464,False,2336.7010276949622,median " grammar Python3; tokens { INDENT, DEDENT } @lexer::members { private java.util.LinkedList tokens = new java.util.LinkedList<>(); private java.util.Stack indents = new java.util.Stack<>(); private int opened = 0; private Token lastToken = null; @Override public void emit(Token t) { super.setToken(t); tokens.offer(t); } @Override public Token nextToken() { if (_input.LA(1) == EOF && !this.indents.isEmpty()) { for (int i = tokens.size() - 1; i >= 0; i--) { if (tokens.get(i).getType() == EOF) { tokens.remove(i); } } this.emit(commonToken(Python3Parser.NEWLINE, ""\\n"")); while (!indents.isEmpty()) { this.emit(createDedent()); indents.pop(); } this.emit(commonToken(Python3Parser.EOF, """")); } Token next = super.nextToken(); if (next.getChannel() == Token.DEFAULT_CHANNEL) { this.lastToken = next; } return tokens.isEmpty() ? next : tokens.poll(); } private Token createDedent() { CommonToken dedent = commonToken(Python3Parser.DEDENT, """"); dedent.setLine(this.lastToken.getLine()); return dedent; } private CommonToken commonToken(int type, String text) { int stop = this.getCharIndex() - 1; int start = text.isEmpty() ? stop : stop - text.length() + 1; return new CommonToken(this._tokenFactorySourcePair, type, DEFAULT_TOKEN_CHANNEL, start, stop); } static int getIndentationCount(String spaces) { int count = 0; for (char ch : spaces.toCharArray()) { switch (ch) { case '\\t': count += 8 - (count % 8); break; default: count++; } } return count; } boolean atStartOfInput() { return super.getCharPositionInLine() == 0 && super.getLine() == 1; } } prog : stmt+; /// single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE single_input : NEWLINE | simple_stmt | compound_stmt NEWLINE ; /// file_input: (NEWLINE | stmt)* ENDMARKER file_input : ( NEWLINE | stmt )* EOF ; /// eval_input: testlist NEWLINE* ENDMARKER eval_input : testlist NEWLINE* EOF ; /// decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE decorator : '@' dotted_name ( '(' arglist? ')' )? NEWLINE ; /// decorators: decorator+ decorators : decorator+ ; /// decorated: decorators (classdef | funcdef) decorated : decorators ( classdef | funcdef ) ; /// funcdef: 'def' NAME parameters ['->' test] ':' suite funcdef : DEF NAME parameters ( '->' test )? ':' suite ; /// parameters: '(' [typedargslist] ')' parameters : '(' (typedargslist)? ')' ; /// typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' /// ['*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef]] /// | '*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef) typedargslist :tfpdef ( '=' test )? ( ',' tfpdef ( '=' test )? )* ( ',' ( '*' tfpdef? ( ',' tfpdef ( '=' test )? )* ( ',' '**' tfpdef )? | '**' tfpdef )? )? | '*' tfpdef? ( ',' tfpdef ( '=' test )? )* ( ',' '**' tfpdef )? | '**' tfpdef ; /// tfpdef: NAME [':' test] tfpdef : NAME( ':' test )? ; /// varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' /// ['*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef]] /// | '*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef) varargslist : vfpdef ( '=' test )? ( ',' vfpdef ( '=' test )? )* ( ',' ( '*' vfpdef? ( ',' vfpdef ( '=' test )? )* ( ',' '**' vfpdef )? | '**' vfpdef )? )? | '*' vfpdef? ( ',' vfpdef ( '=' test )? )* ( ',' '**' vfpdef )? | '**' vfpdef ; /// vfpdef: NAME vfpdef : NAME ; /// stmt: simple_stmt | compound_stmt stmt : simple_stmt | compound_stmt ; /// simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE simple_stmt : small_stmt ( ';' small_stmt )* ';'? NEWLINE ; /// small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | /// import_stmt | global_stmt | nonlocal_stmt | assert_stmt) small_stmt : expr_stmt | del_stmt | pass_stmt | flow_stmt | import_stmt | global_stmt | nonlocal_stmt | assert_stmt ; /// expr_stmt: testlist_star_expr (augassign (yield_expr|testlist) | /// ('=' (yield_expr|testlist_star_expr))*) expr_stmt : testlist_star_expr ( augassign ( yield_expr | testlist) | ( '=' ( yield_expr| testlist_star_expr ) )* ) ; /// testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [','] testlist_star_expr : ( test | star_expr ) ( ',' ( test | star_expr ) )* ','? ; /// augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' | /// '<<=' | '>>=' | '**=' | '//=') augassign : '+=' | '-=' | '*=' | '@=' // PEP 465 | '/=' | '%=' | '&=' | '|=' | '^=' | '<<=' | '>>=' | '**=' | '//=' ; /// del_stmt: 'del' exprlist del_stmt : DEL exprlist ; /// pass_stmt: 'pass' pass_stmt : PASS ; /// flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt flow_stmt : break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt ; /// break_stmt: 'break' break_stmt : BREAK ; /// continue_stmt: 'continue' continue_stmt : CONTINUE ; /// return_stmt: 'return' [testlist] return_stmt : RETURN testlist? ; /// yield_stmt: yield_expr yield_stmt : yield_expr ; /// raise_stmt: 'raise' [test ['from' test]] raise_stmt : RAISE ( test ( FROM test )? )? ; /// import_stmt: import_name | import_from import_stmt : import_name | import_from ; /// import_name: 'import' dotted_as_names import_name : IMPORT dotted_as_names ; /// # note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS /// import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+) /// 'import' ('*' | '(' import_as_names ')' | import_as_names)) import_from : FROM ( ( '.' | '...' )* dotted_name | ('.' | '...')+ ) IMPORT ( '*' | '(' import_as_names ')' | import_as_names ) ; /// import_as_name: NAME ['as' NAME] import_as_name : NAME ( AS NAME )? ; /// dotted_as_name: dotted_name ['as' NAME] dotted_as_name : dotted_name ( AS NAME )? ; /// import_as_names: import_as_name (',' import_as_name)* [','] import_as_names : import_as_name ( ',' import_as_name )* ','? ; /// dotted_as_names: dotted_as_name (',' dotted_as_name)* dotted_as_names : dotted_as_name ( ',' dotted_as_name )* ; /// dotted_name: NAME ('.' NAME)* dotted_name : NAME ( '.' NAME )* ; /// global_stmt: 'global' NAME (',' NAME)* global_stmt : GLOBAL NAME ( ',' NAME )* ; /// nonlocal_stmt: 'nonlocal' NAME (',' NAME)* nonlocal_stmt : NONLOCAL NAME ( ',' NAME )* ; /// assert_stmt: 'assert' test [',' test] assert_stmt : ASSERT test ( ',' test )? ; /// compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated compound_stmt : if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated ; /// if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite] if_stmt : IF test ':' suite ( ELIF elifTest += test ':' elifSuite += suite )* ( ELSE ':' elseSuite = suite )? ; /// while_stmt: 'while' test ':' suite ['else' ':' suite] while_stmt : WHILE test ':' suite ( ELSE ':' suite )? ; /// for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] for_stmt : FOR exprlist IN testlist ':' suite ( ELSE ':' suite )? ; /// try_stmt: ('try' ':' suite /// ((except_clause ':' suite)+ /// ['else' ':' suite] /// ['finally' ':' suite] | /// 'finally' ':' suite)) try_stmt : TRY ':' suite ( ( except_clause ':' suite )+ ( ELSE ':' suite )? ( FINALLY ':' suite )? | FINALLY ':' suite ) ; /// with_stmt: 'with' with_item (',' with_item)* ':' suite with_stmt : WITH with_item ( ',' with_item )* ':' suite ; /// with_item: test ['as' expr] with_item : test ( AS expr )? ; /// # NB compile.c makes sure that the default except clause is last /// except_clause: 'except' [test ['as' NAME]] except_clause : EXCEPT ( test ( AS NAME )? )? ; /// suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT suite : simple_stmt | NEWLINE INDENT stmt+ DEDENT ; /// test: or_test ['if' or_test 'else' test] | lambdef test : or_test ( IF or_test ELSE test )? | lambdef ; /// test_nocond: or_test | lambdef_nocond test_nocond : or_test | lambdef_nocond ; /// lambdef: 'lambda' [varargslist] ':' test lambdef : LAMBDA varargslist? ':' test ; /// lambdef_nocond: 'lambda' [varargslist] ':' test_nocond lambdef_nocond : LAMBDA varargslist? ':' test_nocond ; /// or_test: and_test ('or' and_test)* or_test : and_test ( OR and_test )* ; /// and_test: not_test ('and' not_test)* and_test : not_test ( AND not_test )* ; /// not_test: 'not' not_test | comparison not_test : NOT not_test | comparison ; /// comparison: star_expr (comp_op star_expr)* comparison : star_expr ( comp_op star_expr )* ; /// # <> isn't actually a valid comparison operator in Python. It's here for the /// # sake of a __future__ import described in PEP 401 /// comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' comp_op : '<' | '>' | '==' | '>=' | '<=' | '<>' | '!=' | IN | NOT IN | IS | IS NOT ; /// star_expr: ['*'] expr star_expr : STAR? expr ; /// expr: xor_expr ('|' xor_expr)* expr : xor_expr ( '|' xor_expr )* ; /// xor_expr: and_expr ('^' and_expr)* xor_expr : and_expr ( '^' and_expr )* ; /// and_expr: shift_expr ('&' shift_expr)* and_expr : shift_expr ( '&' shift_expr )* ; /// shift_expr: arith_expr (('<<'|'>>') arith_expr)* shift_expr : arith_expr ( opss += '<<' arith_expr | opss += '>>' arith_expr )* ; /// arith_expr: term (('+'|'-') term)* arith_expr : term ( opss += '+' term | opss += '-' term )* ; /// term: factor (('*'|'/'|'%'|'//') factor)* term : factor ( opss += '*' factor | opss += '/' factor | opss += '%' factor | opss += '//' factor | opss += '@' factor // PEP 465 )* ; /// factor: ('+'|'-'|'~') factor | power factor : op = '+' factor | op = '-' factor | op = '~' factor | power ; /// power: atom trailer* ['**' factor] power : atom trailer* ( '**' factor )? ; /// atom: ('(' [yield_expr|testlist_comp] ')' | /// '[' [testlist_comp] ']' | /// '{' [dictorsetmaker] '}' | /// NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False') atom : '(' ( yield_expr | testlist_comp )? ')' | '[' testlist_comp? ']' | '{' dictorsetmaker? '}' | NAME | number | string+ | '...' | NONE | TRUE | FALSE ; /// testlist_comp: test ( comp_for | (',' test)* [','] ) testlist_comp : test ( comp_for | ( ',' test )* ','? ) ; /// trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME trailer : '(' arglist? ')' | '[' subscriptlist ']' | '.' NAME ; /// subscriptlist: subscript (',' subscript)* [','] subscriptlist : subscript ( ',' subscript )* ','? ; /// subscript: test | [test] ':' [test] [sliceop] subscript : test | test? ':' test? sliceop? ; /// sliceop: ':' [test] sliceop : ':' test? ; /// exprlist: star_expr (',' star_expr)* [','] exprlist : star_expr ( ',' star_expr )* ','? ; /// testlist: test (',' test)* [','] testlist : test ( ',' test )* ','? ; /// dictorsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) | /// (test (comp_for | (',' test)* [','])) ) dictorsetmaker : test ':' test ( comp_for | ( ',' test ':' test )* ','? ) | test ( comp_for | ( ',' test )* ','? ) ; /// classdef: 'class' NAME ['(' [arglist] ')'] ':' suite classdef : CLASS NAME ( '(' arglist? ')' )? ':' suite ; /// arglist: (argument ',')* (argument [','] /// |'*' test (',' argument)* [',' '**' test] /// |'**' test) arglist : ( argument ',' )* ( argument ','? | '*' test ( ',' argument )* ( ',' '**' test )? | '**' test ) ; /// # The reason that keywords are test nodes instead of NAME is that using NAME /// # results in an ambiguity. ast.c makes sure it's a NAME. /// argument: test [comp_for] | test '=' test # Really [keyword '='] test argument : test comp_for? | test '=' test ; /// comp_iter: comp_for | comp_if comp_iter : comp_for | comp_if ; /// comp_for: 'for' exprlist 'in' or_test [comp_iter] comp_for : FOR exprlist IN or_test comp_iter? ; /// comp_if: 'if' test_nocond [comp_iter] comp_if : IF test_nocond comp_iter? ; /// yield_expr: 'yield' [testlist] yield_expr : YIELD yield_arg? ; /// yield_arg: 'from' test | testlist yield_arg : FROM test | testlist ; string : STRING_LITERAL | BYTES_LITERAL ; number : integer | FLOAT_NUMBER | IMAG_NUMBER ; /// integer ::= decimalinteger | octinteger | hexinteger | bininteger integer : DECIMAL_INTEGER | OCT_INTEGER | HEX_INTEGER | BIN_INTEGER ; /* * lexer rules */ DEF : 'def'; RETURN : 'return'; RAISE : 'raise'; FROM : 'from'; IMPORT : 'import'; AS : 'as'; GLOBAL : 'global'; NONLOCAL : 'nonlocal'; ASSERT : 'assert'; IF : 'if'; ELIF : 'elif'; ELSE : 'else'; WHILE : 'while'; FOR : 'for'; IN : 'in'; TRY : 'try'; FINALLY : 'finally'; WITH : 'with'; EXCEPT : 'except'; LAMBDA : 'lambda'; OR : 'or'; AND : 'and'; NOT : 'not'; IS : 'is'; NONE : 'None'; TRUE : 'True'; FALSE : 'False'; CLASS : 'class'; YIELD : 'yield'; DEL : 'del'; PASS : 'pass'; CONTINUE : 'continue'; BREAK : 'break'; NEWLINE : ( {atStartOfInput()}? SPACES | ( '\\r'? '\\n' | '\\r' ) SPACES? ) { String newLine = getText().replaceAll(""[^\\r\\n]+"", """"); String spaces = getText().replaceAll(""[\\r\\n]+"", """"); int next = _input.LA(1); if (opened > 0 || next == '\\r' || next == '\\n' || next == '#') { // If we're inside a list or on a blank line, ignore all indents, // dedents and line breaks. skip(); } else { emit(commonToken(NEWLINE, newLine)); int indent = getIndentationCount(spaces); int previous = indents.isEmpty() ? 0 : indents.peek(); if (indent == previous) { // skip indents of the same size as the present indent-size skip(); } else if (indent > previous) { indents.push(indent); emit(commonToken(Python3Parser.INDENT, spaces)); } else { // Possibly emit more than 1 DEDENT token. while(!indents.isEmpty() && indents.peek() > indent) { this.emit(createDedent()); indents.pop(); } } } } ; /// identifier ::= id_start id_continue* NAME : ID_START ID_CONTINUE* ; /// stringliteral ::= [stringprefix](shortstring | longstring) /// stringprefix ::= ""r"" | ""R"" STRING_LITERAL : [uU]? [rR]? ( SHORT_STRING | LONG_STRING ) ; /// bytesliteral ::= bytesprefix(shortbytes | longbytes) /// bytesprefix ::= ""b"" | ""B"" | ""br"" | ""Br"" | ""bR"" | ""BR"" BYTES_LITERAL : [bB] [rR]? ( SHORT_BYTES | LONG_BYTES ) ; /// decimalinteger ::= nonzerodigit digit* | ""0""+ DECIMAL_INTEGER : NON_ZERO_DIGIT DIGIT* | '0'+ ; /// octinteger ::= ""0"" (""o"" | ""O"") octdigit+ OCT_INTEGER : '0' [oO] OCT_DIGIT+ ; /// hexinteger ::= ""0"" (""x"" | ""X"") hexdigit+ HEX_INTEGER : '0' [xX] HEX_DIGIT+ ; /// bininteger ::= ""0"" (""b"" | ""B"") bindigit+ BIN_INTEGER : '0' [bB] BIN_DIGIT+ ; /// floatnumber ::= pointfloat | exponentfloat FLOAT_NUMBER : POINT_FLOAT | EXPONENT_FLOAT ; /// imagnumber ::= (floatnumber | intpart) (""j"" | ""J"") IMAG_NUMBER : ( FLOAT_NUMBER | INT_PART ) [jJ] ; DOT : '.'; ELLIPSIS : '...'; STAR : '*'; OPEN_PAREN : '(' {opened++;}; CLOSE_PAREN : ')' {opened--;}; COMMA : ','; COLON : ':'; SEMI_COLON : ';'; POWER : '**'; ASSIGN : '='; OPEN_BRACK : '[' {opened++;}; CLOSE_BRACK : ']' {opened--;}; OR_OP : '|'; XOR : '^'; AND_OP : '&'; LEFT_SHIFT : '<<'; RIGHT_SHIFT : '>>'; ADD : '+'; MINUS : '-'; DIV : '/'; MOD : '%'; IDIV : '//'; NOT_OP : '~'; OPEN_BRACE : '{' {opened++;}; CLOSE_BRACE : '}' {opened--;}; LESS_THAN : '<'; GREATER_THAN : '>'; EQUALS : '=='; GT_EQ : '>='; LT_EQ : '<='; NOT_EQ_1 : '<>'; NOT_EQ_2 : '!='; AT : '@'; ARROW : '->'; ADD_ASSIGN : '+='; SUB_ASSIGN : '-='; MULT_ASSIGN : '*='; AT_ASSIGN : '@='; DIV_ASSIGN : '/='; MOD_ASSIGN : '%='; AND_ASSIGN : '&='; OR_ASSIGN : '|='; XOR_ASSIGN : '^='; LEFT_SHIFT_ASSIGN : '<<='; RIGHT_SHIFT_ASSIGN : '>>='; POWER_ASSIGN : '**='; IDIV_ASSIGN : '//='; WWW : ( SPACES | COMMENT | LINE_JOINING ) -> skip ; UNKNOWN_CHAR : . ; /* * fragments */ /// shortstring ::= ""'"" shortstringitem* ""'"" | '""' shortstringitem* '""' /// shortstringitem ::= shortstringchar | stringescapeseq /// shortstringchar ::= fragment SHORT_STRING : '\\'' ( STRING_ESCAPE_SEQ | ~[\\\\\\r\\n'] )* '\\'' | '""' ( STRING_ESCAPE_SEQ | ~[\\\\\\r\\n""] )* '""' ; /// longstring ::= ""'''"" longstringitem* ""'''"" | '""""""' longstringitem* '""""""' fragment LONG_STRING : '\\'\\'\\'' LONG_STRING_ITEM*? '\\'\\'\\'' | '""""""' LONG_STRING_ITEM*? '""""""' ; /// longstringitem ::= longstringchar | stringescapeseq fragment LONG_STRING_ITEM : LONG_STRING_CHAR | STRING_ESCAPE_SEQ ; /// longstringchar ::= fragment LONG_STRING_CHAR : ~'\\\\' ; /// stringescapeseq ::= ""\\"" fragment STRING_ESCAPE_SEQ : '\\\\' . ; /// nonzerodigit ::= ""1""...""9"" fragment NON_ZERO_DIGIT : [1-9] ; /// digit ::= ""0""...""9"" fragment DIGIT : [0-9] ; /// octdigit ::= ""0""...""7"" fragment OCT_DIGIT : [0-7] ; /// hexdigit ::= digit | ""a""...""f"" | ""A""...""F"" fragment HEX_DIGIT : [0-9a-fA-F] ; /// bindigit ::= ""0"" | ""1"" fragment BIN_DIGIT : [01] ; /// pointfloat ::= [intpart] fraction | intpart ""."" fragment POINT_FLOAT : INT_PART? FRACTION | INT_PART '.' ; /// exponentfloat ::= (intpart | pointfloat) exponent fragment EXPONENT_FLOAT : ( INT_PART | POINT_FLOAT ) EXPONENT ; /// intpart ::= digit+ fragment INT_PART : DIGIT+ ; /// fraction ::= ""."" digit+ fragment FRACTION : '.' DIGIT+ ; /// exponent ::= (""e"" | ""E"") [""+"" | ""-""] digit+ fragment EXPONENT : [eE] [+-]? DIGIT+ ; /// shortbytes ::= ""'"" shortbytesitem* ""'"" | '""' shortbytesitem* '""' /// shortbytesitem ::= shortbyteschar | bytesescapeseq fragment SHORT_BYTES : '\\'' ( SHORT_BYTES_CHAR_NO_SINGLE_QUOTE | BYTES_ESCAPE_SEQ )* '\\'' | '""' ( SHORT_BYTES_CHAR_NO_DOUBLE_QUOTE | BYTES_ESCAPE_SEQ )* '""' ; /// longbytes ::= ""'''"" longbytesitem* ""'''"" | '""""""' longbytesitem* '""""""' fragment LONG_BYTES : '\\'\\'\\'' LONG_BYTES_ITEM*? '\\'\\'\\'' | '""""""' LONG_BYTES_ITEM*? '""""""' ; /// longbytesitem ::= longbyteschar | bytesescapeseq fragment LONG_BYTES_ITEM : LONG_BYTES_CHAR | BYTES_ESCAPE_SEQ ; /// shortbyteschar ::= fragment SHORT_BYTES_CHAR_NO_SINGLE_QUOTE : [\\u0000-\\u0009] | [\\u000B-\\u000C] | [\\u000E-\\u0026] | [\\u0028-\\u005B] | [\\u005D-\\u007F] ; fragment SHORT_BYTES_CHAR_NO_DOUBLE_QUOTE : [\\u0000-\\u0009] | [\\u000B-\\u000C] | [\\u000E-\\u0021] | [\\u0023-\\u005B] | [\\u005D-\\u007F] ; /// longbyteschar ::= fragment LONG_BYTES_CHAR : [\\u0000-\\u005B] | [\\u005D-\\u007F] ; /// bytesescapeseq ::= ""\\"" fragment BYTES_ESCAPE_SEQ : '\\\\' [\\u0000-\\u007F] ; fragment SPACES : [ \\t]+ ; fragment COMMENT : '#' ~[\\r\\n]* ; fragment LINE_JOINING : '\\\\' SPACES? ( '\\r'? '\\n' | '\\r' ) ; /// id_start ::= fragment ID_START : '_' | [A-Z] | [a-z] | '\\u00AA' | '\\u00B5' | '\\u00BA' | [\\u00C0-\\u00D6] | [\\u00D8-\\u00F6] | [\\u00F8-\\u01BA] | '\\u01BB' | [\\u01BC-\\u01BF] | [\\u01C0-\\u01C3] | [\\u01C4-\\u0241] | [\\u0250-\\u02AF] | [\\u02B0-\\u02C1] | [\\u02C6-\\u02D1] | [\\u02E0-\\u02E4] | '\\u02EE' | '\\u037A' | '\\u0386' | [\\u0388-\\u038A] | '\\u038C' | [\\u038E-\\u03A1] | [\\u03A3-\\u03CE] | [\\u03D0-\\u03F5] | [\\u03F7-\\u0481] | [\\u048A-\\u04CE] | [\\u04D0-\\u04F9] | [\\u0500-\\u050F] | [\\u0531-\\u0556] | '\\u0559' | [\\u0561-\\u0587] | [\\u05D0-\\u05EA] | [\\u05F0-\\u05F2] | [\\u0621-\\u063A] | '\\u0640' | [\\u0641-\\u064A] | [\\u066E-\\u066F] | [\\u0671-\\u06D3] | '\\u06D5' | [\\u06E5-\\u06E6] | [\\u06EE-\\u06EF] | [\\u06FA-\\u06FC] | '\\u06FF' | '\\u0710' | [\\u0712-\\u072F] | [\\u074D-\\u076D] | [\\u0780-\\u07A5] | '\\u07B1' | [\\u0904-\\u0939] | '\\u093D' | '\\u0950' | [\\u0958-\\u0961] | '\\u097D' | [\\u0985-\\u098C] | [\\u098F-\\u0990] | [\\u0993-\\u09A8] | [\\u09AA-\\u09B0] | '\\u09B2' | [\\u09B6-\\u09B9] | '\\u09BD' | '\\u09CE' | [\\u09DC-\\u09DD] | [\\u09DF-\\u09E1] | [\\u09F0-\\u09F1] | [\\u0A05-\\u0A0A] | [\\u0A0F-\\u0A10] | [\\u0A13-\\u0A28] | [\\u0A2A-\\u0A30] | [\\u0A32-\\u0A33] | [\\u0A35-\\u0A36] | [\\u0A38-\\u0A39] | [\\u0A59-\\u0A5C] | '\\u0A5E' | [\\u0A72-\\u0A74] | [\\u0A85-\\u0A8D] | [\\u0A8F-\\u0A91] | [\\u0A93-\\u0AA8] | [\\u0AAA-\\u0AB0] | [\\u0AB2-\\u0AB3] | [\\u0AB5-\\u0AB9] | '\\u0ABD' | '\\u0AD0' | [\\u0AE0-\\u0AE1] | [\\u0B05-\\u0B0C] | [\\u0B0F-\\u0B10] | [\\u0B13-\\u0B28] | [\\u0B2A-\\u0B30] | [\\u0B32-\\u0B33] | [\\u0B35-\\u0B39] | '\\u0B3D' | [\\u0B5C-\\u0B5D] | [\\u0B5F-\\u0B61] | '\\u0B71' | '\\u0B83' | [\\u0B85-\\u0B8A] | [\\u0B8E-\\u0B90] | [\\u0B92-\\u0B95] | [\\u0B99-\\u0B9A] | '\\u0B9C' | [\\u0B9E-\\u0B9F] | [\\u0BA3-\\u0BA4] | [\\u0BA8-\\u0BAA] | [\\u0BAE-\\u0BB9] | [\\u0C05-\\u0C0C] | [\\u0C0E-\\u0C10] | [\\u0C12-\\u0C28] | [\\u0C2A-\\u0C33] | [\\u0C35-\\u0C39] | [\\u0C60-\\u0C61] | [\\u0C85-\\u0C8C] | [\\u0C8E-\\u0C90] | [\\u0C92-\\u0CA8] | [\\u0CAA-\\u0CB3] | [\\u0CB5-\\u0CB9] | '\\u0CBD' | '\\u0CDE' | [\\u0CE0-\\u0CE1] | [\\u0D05-\\u0D0C] | [\\u0D0E-\\u0D10] | [\\u0D12-\\u0D28] | [\\u0D2A-\\u0D39] | [\\u0D60-\\u0D61] | [\\u0D85-\\u0D96] | [\\u0D9A-\\u0DB1] | [\\u0DB3-\\u0DBB] | '\\u0DBD' | [\\u0DC0-\\u0DC6] | [\\u0E01-\\u0E30] | [\\u0E32-\\u0E33] | [\\u0E40-\\u0E45] | '\\u0E46' | [\\u0E81-\\u0E82] | '\\u0E84' | [\\u0E87-\\u0E88] | '\\u0E8A' | '\\u0E8D' | [\\u0E94-\\u0E97] | [\\u0E99-\\u0E9F] | [\\u0EA1-\\u0EA3] | '\\u0EA5' | '\\u0EA7' | [\\u0EAA-\\u0EAB] | [\\u0EAD-\\u0EB0] | [\\u0EB2-\\u0EB3] | '\\u0EBD' | [\\u0EC0-\\u0EC4] | '\\u0EC6' | [\\u0EDC-\\u0EDD] | '\\u0F00' | [\\u0F40-\\u0F47] | [\\u0F49-\\u0F6A] | [\\u0F88-\\u0F8B] | [\\u1000-\\u1021] | [\\u1023-\\u1027] | [\\u1029-\\u102A] | [\\u1050-\\u1055] | [\\u10A0-\\u10C5] | [\\u10D0-\\u10FA] | '\\u10FC' | [\\u1100-\\u1159] | [\\u115F-\\u11A2] | [\\u11A8-\\u11F9] | [\\u1200-\\u1248] | [\\u124A-\\u124D] | [\\u1250-\\u1256] | '\\u1258' | [\\u125A-\\u125D] | [\\u1260-\\u1288] | [\\u128A-\\u128D] | [\\u1290-\\u12B0] | [\\u12B2-\\u12B5] | [\\u12B8-\\u12BE] | '\\u12C0' | [\\u12C2-\\u12C5] | [\\u12C8-\\u12D6] | [\\u12D8-\\u1310] | [\\u1312-\\u1315] | [\\u1318-\\u135A] | [\\u1380-\\u138F] | [\\u13A0-\\u13F4] | [\\u1401-\\u166C] | [\\u166F-\\u1676] | [\\u1681-\\u169A] | [\\u16A0-\\u16EA] | [\\u16EE-\\u16F0] | [\\u1700-\\u170C] | [\\u170E-\\u1711] | [\\u1720-\\u1731] | [\\u1740-\\u1751] | [\\u1760-\\u176C] | [\\u176E-\\u1770] | [\\u1780-\\u17B3] | '\\u17D7' | '\\u17DC' | [\\u1820-\\u1842] | '\\u1843' | [\\u1844-\\u1877] | [\\u1880-\\u18A8] | [\\u1900-\\u191C] | [\\u1950-\\u196D] | [\\u1970-\\u1974] | [\\u1980-\\u19A9] | [\\u19C1-\\u19C7] | [\\u1A00-\\u1A16] | [\\u1D00-\\u1D2B] | [\\u1D2C-\\u1D61] | [\\u1D62-\\u1D77] | '\\u1D78' | [\\u1D79-\\u1D9A] | [\\u1D9B-\\u1DBF] | [\\u1E00-\\u1E9B] | [\\u1EA0-\\u1EF9] | [\\u1F00-\\u1F15] | [\\u1F18-\\u1F1D] | [\\u1F20-\\u1F45] | [\\u1F48-\\u1F4D] | [\\u1F50-\\u1F57] | '\\u1F59' | '\\u1F5B' | '\\u1F5D' | [\\u1F5F-\\u1F7D] | [\\u1F80-\\u1FB4] | [\\u1FB6-\\u1FBC] | '\\u1FBE' | [\\u1FC2-\\u1FC4] | [\\u1FC6-\\u1FCC] | [\\u1FD0-\\u1FD3] | [\\u1FD6-\\u1FDB] | [\\u1FE0-\\u1FEC] | [\\u1FF2-\\u1FF4] | [\\u1FF6-\\u1FFC] | '\\u2071' | '\\u207F' | [\\u2090-\\u2094] | '\\u2102' | '\\u2107' | [\\u210A-\\u2113] | '\\u2115' | '\\u2118' | [\\u2119-\\u211D] | '\\u2124' | '\\u2126' | '\\u2128' | [\\u212A-\\u212D] | '\\u212E' | [\\u212F-\\u2131] | [\\u2133-\\u2134] | [\\u2135-\\u2138] | '\\u2139' | [\\u213C-\\u213F] | [\\u2145-\\u2149] | [\\u2160-\\u2183] | [\\u2C00-\\u2C2E] | [\\u2C30-\\u2C5E] | [\\u2C80-\\u2CE4] | [\\u2D00-\\u2D25] | [\\u2D30-\\u2D65] | '\\u2D6F' | [\\u2D80-\\u2D96] | [\\u2DA0-\\u2DA6] | [\\u2DA8-\\u2DAE] | [\\u2DB0-\\u2DB6] | [\\u2DB8-\\u2DBE] | [\\u2DC0-\\u2DC6] | [\\u2DC8-\\u2DCE] | [\\u2DD0-\\u2DD6] | [\\u2DD8-\\u2DDE] | '\\u3005' | '\\u3006' | '\\u3007' | [\\u3021-\\u3029] | [\\u3031-\\u3035] | [\\u3038-\\u303A] | '\\u303B' | '\\u303C' | [\\u3041-\\u3096] | [\\u309B-\\u309C] | [\\u309D-\\u309E] | '\\u309F' | [\\u30A1-\\u30FA] | [\\u30FC-\\u30FE] | '\\u30FF' | [\\u3105-\\u312C] | [\\u3131-\\u318E] | [\\u31A0-\\u31B7] | [\\u31F0-\\u31FF] | [\\u3400-\\u4DB5] | [\\u4E00-\\u9FBB] | [\\uA000-\\uA014] | '\\uA015' | [\\uA016-\\uA48C] | [\\uA800-\\uA801] | [\\uA803-\\uA805] | [\\uA807-\\uA80A] | [\\uA80C-\\uA822] | [\\uAC00-\\uD7A3] | [\\uF900-\\uFA2D] | [\\uFA30-\\uFA6A] | [\\uFA70-\\uFAD9] | [\\uFB00-\\uFB06] | [\\uFB13-\\uFB17] | '\\uFB1D' | [\\uFB1F-\\uFB28] | [\\uFB2A-\\uFB36] | [\\uFB38-\\uFB3C] | '\\uFB3E' | [\\uFB40-\\uFB41] | [\\uFB43-\\uFB44] | [\\uFB46-\\uFBB1] | [\\uFBD3-\\uFD3D] | [\\uFD50-\\uFD8F] | [\\uFD92-\\uFDC7] | [\\uFDF0-\\uFDFB] | [\\uFE70-\\uFE74] | [\\uFE76-\\uFEFC] | [\\uFF21-\\uFF3A] | [\\uFF41-\\uFF5A] | [\\uFF66-\\uFF6F] | '\\uFF70' | [\\uFF71-\\uFF9D] | [\\uFF9E-\\uFF9F] | [\\uFFA0-\\uFFBE] | [\\uFFC2-\\uFFC7] | [\\uFFCA-\\uFFCF] | [\\uFFD2-\\uFFD7] | [\\uFFDA-\\uFFDC] ; /// id_continue ::= fragment ID_CONTINUE : ID_START | [0-9] | [\\u0300-\\u036F] | [\\u0483-\\u0486] | [\\u0591-\\u05B9] | [\\u05BB-\\u05BD] | '\\u05BF' | [\\u05C1-\\u05C2] | [\\u05C4-\\u05C5] | '\\u05C7' | [\\u0610-\\u0615] | [\\u064B-\\u065E] | [\\u0660-\\u0669] | '\\u0670' | [\\u06D6-\\u06DC] | [\\u06DF-\\u06E4] | [\\u06E7-\\u06E8] | [\\u06EA-\\u06ED] | [\\u06F0-\\u06F9] | '\\u0711' | [\\u0730-\\u074A] | [\\u07A6-\\u07B0] | [\\u0901-\\u0902] | '\\u0903' | '\\u093C' | [\\u093E-\\u0940] | [\\u0941-\\u0948] | [\\u0949-\\u094C] | '\\u094D' | [\\u0951-\\u0954] | [\\u0962-\\u0963] | [\\u0966-\\u096F] | '\\u0981' | [\\u0982-\\u0983] | '\\u09BC' | [\\u09BE-\\u09C0] | [\\u09C1-\\u09C4] | [\\u09C7-\\u09C8] | [\\u09CB-\\u09CC] | '\\u09CD' | '\\u09D7' | [\\u09E2-\\u09E3] | [\\u09E6-\\u09EF] | [\\u0A01-\\u0A02] | '\\u0A03' | '\\u0A3C' | [\\u0A3E-\\u0A40] | [\\u0A41-\\u0A42] | [\\u0A47-\\u0A48] | [\\u0A4B-\\u0A4D] | [\\u0A66-\\u0A6F] | [\\u0A70-\\u0A71] | [\\u0A81-\\u0A82] | '\\u0A83' | '\\u0ABC' | [\\u0ABE-\\u0AC0] | [\\u0AC1-\\u0AC5] | [\\u0AC7-\\u0AC8] | '\\u0AC9' | [\\u0ACB-\\u0ACC] | '\\u0ACD' | [\\u0AE2-\\u0AE3] | [\\u0AE6-\\u0AEF] | '\\u0B01' | [\\u0B02-\\u0B03] | '\\u0B3C' | '\\u0B3E' | '\\u0B3F' | '\\u0B40' | [\\u0B41-\\u0B43] | [\\u0B47-\\u0B48] | [\\u0B4B-\\u0B4C] | '\\u0B4D' | '\\u0B56' | '\\u0B57' | [\\u0B66-\\u0B6F] | '\\u0B82' | [\\u0BBE-\\u0BBF] | '\\u0BC0' | [\\u0BC1-\\u0BC2] | [\\u0BC6-\\u0BC8] | [\\u0BCA-\\u0BCC] | '\\u0BCD' | '\\u0BD7' | [\\u0BE6-\\u0BEF] | [\\u0C01-\\u0C03] | [\\u0C3E-\\u0C40] | [\\u0C41-\\u0C44] | [\\u0C46-\\u0C48] | [\\u0C4A-\\u0C4D] | [\\u0C55-\\u0C56] | [\\u0C66-\\u0C6F] | [\\u0C82-\\u0C83] | '\\u0CBC' | '\\u0CBE' | '\\u0CBF' | [\\u0CC0-\\u0CC4] | '\\u0CC6' | [\\u0CC7-\\u0CC8] | [\\u0CCA-\\u0CCB] | [\\u0CCC-\\u0CCD] | [\\u0CD5-\\u0CD6] | [\\u0CE6-\\u0CEF] | [\\u0D02-\\u0D03] | [\\u0D3E-\\u0D40] | [\\u0D41-\\u0D43] | [\\u0D46-\\u0D48] | [\\u0D4A-\\u0D4C] | '\\u0D4D' | '\\u0D57' | [\\u0D66-\\u0D6F] | [\\u0D82-\\u0D83] | '\\u0DCA' | [\\u0DCF-\\u0DD1] | [\\u0DD2-\\u0DD4] | '\\u0DD6' | [\\u0DD8-\\u0DDF] | [\\u0DF2-\\u0DF3] | '\\u0E31' | [\\u0E34-\\u0E3A] | [\\u0E47-\\u0E4E] | [\\u0E50-\\u0E59] | '\\u0EB1' | [\\u0EB4-\\u0EB9] | [\\u0EBB-\\u0EBC] | [\\u0EC8-\\u0ECD] | [\\u0ED0-\\u0ED9] | [\\u0F18-\\u0F19] | [\\u0F20-\\u0F29] | '\\u0F35' | '\\u0F37' | '\\u0F39' | [\\u0F3E-\\u0F3F] | [\\u0F71-\\u0F7E] | '\\u0F7F' | [\\u0F80-\\u0F84] | [\\u0F86-\\u0F87] | [\\u0F90-\\u0F97] | [\\u0F99-\\u0FBC] | '\\u0FC6' | '\\u102C' | [\\u102D-\\u1030] | '\\u1031' | '\\u1032' | [\\u1036-\\u1037] | '\\u1038' | '\\u1039' | [\\u1040-\\u1049] | [\\u1056-\\u1057] | [\\u1058-\\u1059] | '\\u135F' | [\\u1369-\\u1371] | [\\u1712-\\u1714] | [\\u1732-\\u1734] | [\\u1752-\\u1753] | [\\u1772-\\u1773] | '\\u17B6' | [\\u17B7-\\u17BD] | [\\u17BE-\\u17C5] | '\\u17C6' | [\\u17C7-\\u17C8] | [\\u17C9-\\u17D3] | '\\u17DD' | [\\u17E0-\\u17E9] | [\\u180B-\\u180D] | [\\u1810-\\u1819] | '\\u18A9' | [\\u1920-\\u1922] | [\\u1923-\\u1926] | [\\u1927-\\u1928] | [\\u1929-\\u192B] | [\\u1930-\\u1931] | '\\u1932' | [\\u1933-\\u1938] | [\\u1939-\\u193B] | [\\u1946-\\u194F] | [\\u19B0-\\u19C0] | [\\u19C8-\\u19C9] | [\\u19D0-\\u19D9] | [\\u1A17-\\u1A18] | [\\u1A19-\\u1A1B] | [\\u1DC0-\\u1DC3] | [\\u203F-\\u2040] | '\\u2054' | [\\u20D0-\\u20DC] | '\\u20E1' | [\\u20E5-\\u20EB] | [\\u302A-\\u302F] | [\\u3099-\\u309A] | '\\uA802' | '\\uA806' | '\\uA80B' | [\\uA823-\\uA824] | [\\uA825-\\uA826] | '\\uA827' | '\\uFB1E' | [\\uFE00-\\uFE0F] | [\\uFE20-\\uFE23] | [\\uFE33-\\uFE34] | [\\uFE4D-\\uFE4F] | [\\uFF10-\\uFF19] | '\\uFF3F' ; ",12317,False,2414.62917156235,median "/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * ""License""); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ grammar Gremlin; /********************************************* PARSER RULES **********************************************/ queryList : query (SEMI? query)* SEMI? EOF ; query : traversalSource | traversalSource DOT transactionPart | rootTraversal | rootTraversal DOT traversalTerminalMethod | query DOT 'toString' LPAREN RPAREN | emptyQuery ; emptyQuery : EmptyStringLiteral ; traversalSource : TRAVERSAL_ROOT | TRAVERSAL_ROOT DOT traversalSourceSelfMethod | traversalSource DOT traversalSourceSelfMethod ; transactionPart : 'tx' LPAREN RPAREN DOT 'begin' LPAREN RPAREN | 'tx' LPAREN RPAREN DOT 'commit' LPAREN RPAREN | 'tx' LPAREN RPAREN DOT 'rollback' LPAREN RPAREN ; rootTraversal : traversalSource DOT traversalSourceSpawnMethod | traversalSource DOT traversalSourceSpawnMethod DOT chainedTraversal | traversalSource DOT traversalSourceSpawnMethod DOT chainedParentOfGraphTraversal ; traversalSourceSelfMethod : traversalSourceSelfMethod_withBulk | traversalSourceSelfMethod_withPath | traversalSourceSelfMethod_withSack | traversalSourceSelfMethod_withSideEffect | traversalSourceSelfMethod_withStrategies | traversalSourceSelfMethod_with ; traversalSourceSelfMethod_withBulk : 'withBulk' LPAREN booleanLiteral RPAREN ; traversalSourceSelfMethod_withPath : 'withPath' LPAREN RPAREN ; traversalSourceSelfMethod_withSack : 'withSack' LPAREN genericLiteral RPAREN | 'withSack' LPAREN genericLiteral COMMA traversalOperator RPAREN ; traversalSourceSelfMethod_withSideEffect : 'withSideEffect' LPAREN stringLiteral COMMA genericLiteral RPAREN ; traversalSourceSelfMethod_withStrategies : 'withStrategies' LPAREN traversalStrategy (COMMA traversalStrategyList)? RPAREN ; traversalSourceSelfMethod_with : 'with' LPAREN stringLiteral RPAREN | 'with' LPAREN stringLiteral COMMA genericLiteral RPAREN ; traversalSourceSpawnMethod : traversalSourceSpawnMethod_addE | traversalSourceSpawnMethod_addV | traversalSourceSpawnMethod_E | traversalSourceSpawnMethod_V | traversalSourceSpawnMethod_mergeE | traversalSourceSpawnMethod_mergeV | traversalSourceSpawnMethod_inject | traversalSourceSpawnMethod_io | traversalSourceSpawnMethod_call ; traversalSourceSpawnMethod_addE : 'addE' LPAREN stringLiteral RPAREN | 'addE' LPAREN nestedTraversal RPAREN ; traversalSourceSpawnMethod_addV : 'addV' LPAREN RPAREN | 'addV' LPAREN stringLiteral RPAREN | 'addV' LPAREN nestedTraversal RPAREN ; traversalSourceSpawnMethod_E : 'E' LPAREN genericLiteralList RPAREN ; traversalSourceSpawnMethod_V : 'V' LPAREN genericLiteralList RPAREN ; traversalSourceSpawnMethod_inject : 'inject' LPAREN genericLiteralList RPAREN ; traversalSourceSpawnMethod_io : 'io' LPAREN stringLiteral RPAREN ; traversalSourceSpawnMethod_mergeV : 'mergeV' LPAREN (genericLiteralMap | nullLiteral) RPAREN #traversalSourceSpawnMethod_mergeV_Map | 'mergeV' LPAREN nestedTraversal RPAREN #traversalSourceSpawnMethod_mergeV_Traversal ; traversalSourceSpawnMethod_mergeE : 'mergeE' LPAREN (genericLiteralMap | nullLiteral) RPAREN #traversalSourceSpawnMethod_mergeE_Map | 'mergeE' LPAREN nestedTraversal RPAREN #traversalSourceSpawnMethod_mergeE_Traversal ; traversalSourceSpawnMethod_call : 'call' LPAREN RPAREN #traversalSourceSpawnMethod_call_empty | 'call' LPAREN stringLiteral RPAREN #traversalSourceSpawnMethod_call_string | 'call' LPAREN stringLiteral COMMA genericLiteralMap RPAREN #traversalSourceSpawnMethod_call_string_map | 'call' LPAREN stringLiteral COMMA nestedTraversal RPAREN #traversalSourceSpawnMethod_call_string_traversal | 'call' LPAREN stringLiteral COMMA genericLiteralMap COMMA nestedTraversal RPAREN #traversalSourceSpawnMethod_call_string_map_traversal ; chainedTraversal : traversalMethod | chainedTraversal DOT traversalMethod | chainedTraversal DOT chainedParentOfGraphTraversal ; chainedParentOfGraphTraversal : traversalSelfMethod | chainedParentOfGraphTraversal DOT traversalSelfMethod ; nestedTraversal : rootTraversal | chainedTraversal | ANON_TRAVERSAL_ROOT DOT chainedTraversal ; terminatedTraversal : rootTraversal DOT traversalTerminalMethod ; /********************************************* GENERATED GRAMMAR - DO NOT CHANGE **********************************************/ traversalMethod : traversalMethod_V | traversalMethod_addE | traversalMethod_addV | traversalMethod_mergeE | traversalMethod_mergeV | traversalMethod_aggregate | traversalMethod_and | traversalMethod_as | traversalMethod_barrier | traversalMethod_both | traversalMethod_bothE | traversalMethod_bothV | traversalMethod_branch | traversalMethod_by | traversalMethod_cap | traversalMethod_choose | traversalMethod_coalesce | traversalMethod_coin | traversalMethod_connectedComponent | traversalMethod_constant | traversalMethod_count | traversalMethod_cyclicPath | traversalMethod_dedup | traversalMethod_drop | traversalMethod_elementMap | traversalMethod_emit | traversalMethod_filter | traversalMethod_flatMap | traversalMethod_fold | traversalMethod_from | traversalMethod_group | traversalMethod_groupCount | traversalMethod_has | traversalMethod_hasId | traversalMethod_hasKey | traversalMethod_hasLabel | traversalMethod_hasNot | traversalMethod_hasValue | traversalMethod_id | traversalMethod_identity | traversalMethod_in | traversalMethod_inE | traversalMethod_inV | traversalMethod_index | traversalMethod_inject | traversalMethod_is | traversalMethod_key | traversalMethod_label | traversalMethod_limit | traversalMethod_local | traversalMethod_loops | traversalMethod_map | traversalMethod_match | traversalMethod_math | traversalMethod_max | traversalMethod_mean | traversalMethod_min | traversalMethod_not | traversalMethod_option | traversalMethod_optional | traversalMethod_or | traversalMethod_order | traversalMethod_otherV | traversalMethod_out | traversalMethod_outE | traversalMethod_outV | traversalMethod_pageRank | traversalMethod_path | traversalMethod_peerPressure | traversalMethod_profile | traversalMethod_project | traversalMethod_properties | traversalMethod_property | traversalMethod_propertyMap | traversalMethod_range | traversalMethod_read | traversalMethod_repeat | traversalMethod_sack | traversalMethod_sample | traversalMethod_select | traversalMethod_shortestPath | traversalMethod_sideEffect | traversalMethod_simplePath | traversalMethod_skip | traversalMethod_store | traversalMethod_subgraph | traversalMethod_sum | traversalMethod_tail | traversalMethod_fail | traversalMethod_timeLimit | traversalMethod_times | traversalMethod_to | traversalMethod_toE | traversalMethod_toV | traversalMethod_tree | traversalMethod_unfold | traversalMethod_union | traversalMethod_until | traversalMethod_value | traversalMethod_valueMap | traversalMethod_values | traversalMethod_where | traversalMethod_with | traversalMethod_write | traversalMethod_element | traversalMethod_call ; traversalMethod_V : 'V' LPAREN genericLiteralList RPAREN ; traversalMethod_addE : 'addE' LPAREN stringLiteral RPAREN #traversalMethod_addE_String | 'addE' LPAREN nestedTraversal RPAREN #traversalMethod_addE_Traversal ; traversalMethod_addV : 'addV' LPAREN RPAREN #traversalMethod_addV_Empty | 'addV' LPAREN stringLiteral RPAREN #traversalMethod_addV_String | 'addV' LPAREN nestedTraversal RPAREN #traversalMethod_addV_Traversal ; traversalMethod_mergeV : 'mergeV' LPAREN RPAREN #traversalMethod_mergeV_empty | 'mergeV' LPAREN (genericLiteralMap | nullLiteral) RPAREN #traversalMethod_mergeV_Map | 'mergeV' LPAREN nestedTraversal RPAREN #traversalMethod_mergeV_Traversal ; traversalMethod_mergeE : 'mergeE' LPAREN RPAREN #traversalMethod_mergeE_empty | 'mergeE' LPAREN (genericLiteralMap | nullLiteral) RPAREN #traversalMethod_mergeE_Map | 'mergeE' LPAREN nestedTraversal RPAREN #traversalMethod_mergeE_Traversal ; traversalMethod_aggregate : 'aggregate' LPAREN traversalScope COMMA stringLiteral RPAREN #traversalMethod_aggregate_Scope_String | 'aggregate' LPAREN stringLiteral RPAREN #traversalMethod_aggregate_String ; traversalMethod_and : 'and' LPAREN nestedTraversalList RPAREN ; traversalMethod_as : 'as' LPAREN stringLiteral (COMMA stringLiteralList)? RPAREN ; traversalMethod_barrier : 'barrier' LPAREN traversalSackMethod RPAREN #traversalMethod_barrier_Consumer | 'barrier' LPAREN RPAREN #traversalMethod_barrier_Empty | 'barrier' LPAREN integerLiteral RPAREN #traversalMethod_barrier_int ; traversalMethod_both : 'both' LPAREN stringLiteralList RPAREN ; traversalMethod_bothE : 'bothE' LPAREN stringLiteralList RPAREN ; traversalMethod_bothV : 'bothV' LPAREN RPAREN ; traversalMethod_branch : 'branch' LPAREN nestedTraversal RPAREN ; traversalMethod_by : 'by' LPAREN traversalComparator RPAREN #traversalMethod_by_Comparator | 'by' LPAREN RPAREN #traversalMethod_by_Empty | 'by' LPAREN traversalFunction RPAREN #traversalMethod_by_Function | 'by' LPAREN traversalFunction COMMA traversalComparator RPAREN #traversalMethod_by_Function_Comparator | 'by' LPAREN traversalOrder RPAREN #traversalMethod_by_Order | 'by' LPAREN stringLiteral RPAREN #traversalMethod_by_String | 'by' LPAREN stringLiteral COMMA traversalComparator RPAREN #traversalMethod_by_String_Comparator | 'by' LPAREN traversalToken RPAREN #traversalMethod_by_T | 'by' LPAREN nestedTraversal RPAREN #traversalMethod_by_Traversal | 'by' LPAREN nestedTraversal COMMA traversalComparator RPAREN #traversalMethod_by_Traversal_Comparator ; traversalMethod_cap : 'cap' LPAREN stringLiteral (COMMA stringLiteralList)? RPAREN ; traversalMethod_choose : 'choose' LPAREN traversalFunction RPAREN #traversalMethod_choose_Function | 'choose' LPAREN traversalPredicate COMMA nestedTraversal RPAREN #traversalMethod_choose_Predicate_Traversal | 'choose' LPAREN traversalPredicate COMMA nestedTraversal COMMA nestedTraversal RPAREN #traversalMethod_choose_Predicate_Traversal_Traversal | 'choose' LPAREN nestedTraversal RPAREN #traversalMethod_choose_Traversal | 'choose' LPAREN nestedTraversal COMMA nestedTraversal RPAREN #traversalMethod_choose_Traversal_Traversal | 'choose' LPAREN nestedTraversal COMMA nestedTraversal COMMA nestedTraversal RPAREN #traversalMethod_choose_Traversal_Traversal_Traversal ; traversalMethod_coalesce : 'coalesce' LPAREN nestedTraversalList RPAREN ; traversalMethod_coin : 'coin' LPAREN floatLiteral RPAREN ; traversalMethod_connectedComponent : 'connectedComponent' LPAREN RPAREN ; traversalMethod_constant : 'constant' LPAREN genericLiteral RPAREN ; traversalMethod_count : 'count' LPAREN RPAREN #traversalMethod_count_Empty | 'count' LPAREN traversalScope RPAREN #traversalMethod_count_Scope ; traversalMethod_cyclicPath : 'cyclicPath' LPAREN RPAREN ; traversalMethod_dedup : 'dedup' LPAREN traversalScope (COMMA stringLiteralList)? RPAREN #traversalMethod_dedup_Scope_String | 'dedup' LPAREN stringLiteralList RPAREN #traversalMethod_dedup_String ; traversalMethod_drop : 'drop' LPAREN RPAREN ; traversalMethod_elementMap : 'elementMap' LPAREN stringLiteralList RPAREN ; traversalMethod_emit : 'emit' LPAREN RPAREN #traversalMethod_emit_Empty | 'emit' LPAREN traversalPredicate RPAREN #traversalMethod_emit_Predicate | 'emit' LPAREN nestedTraversal RPAREN #traversalMethod_emit_Traversal ; traversalMethod_filter : 'filter' LPAREN traversalPredicate RPAREN #traversalMethod_filter_Predicate | 'filter' LPAREN nestedTraversal RPAREN #traversalMethod_filter_Traversal ; traversalMethod_flatMap : 'flatMap' LPAREN nestedTraversal RPAREN ; traversalMethod_fold : 'fold' LPAREN RPAREN #traversalMethod_fold_Empty | 'fold' LPAREN genericLiteral COMMA traversalBiFunction RPAREN #traversalMethod_fold_Object_BiFunction ; traversalMethod_from : 'from' LPAREN stringLiteral RPAREN #traversalMethod_from_String | 'from' LPAREN structureVertex RPAREN #traversalMethod_from_Vertex | 'from' LPAREN nestedTraversal RPAREN #traversalMethod_from_Traversal ; traversalMethod_group : 'group' LPAREN RPAREN #traversalMethod_group_Empty | 'group' LPAREN stringLiteral RPAREN #traversalMethod_group_String ; traversalMethod_groupCount : 'groupCount' LPAREN RPAREN #traversalMethod_groupCount_Empty | 'groupCount' LPAREN stringLiteral RPAREN #traversalMethod_groupCount_String ; traversalMethod_has : 'has' LPAREN stringLiteral RPAREN #traversalMethod_has_String | 'has' LPAREN stringLiteral COMMA genericLiteral RPAREN #traversalMethod_has_String_Object | 'has' LPAREN stringLiteral COMMA traversalPredicate RPAREN #traversalMethod_has_String_P | 'has' LPAREN stringLiteral COMMA stringLiteral COMMA genericLiteral RPAREN #traversalMethod_has_String_String_Object | 'has' LPAREN stringLiteral COMMA stringLiteral COMMA traversalPredicate RPAREN #traversalMethod_has_String_String_P | 'has' LPAREN stringLiteral COMMA nestedTraversal RPAREN #traversalMethod_has_String_Traversal | 'has' LPAREN traversalToken COMMA genericLiteral RPAREN #traversalMethod_has_T_Object | 'has' LPAREN traversalToken COMMA traversalPredicate RPAREN #traversalMethod_has_T_P | 'has' LPAREN traversalToken COMMA nestedTraversal RPAREN #traversalMethod_has_T_Traversal ; traversalMethod_hasId : 'hasId' LPAREN genericLiteral (COMMA genericLiteralList)? RPAREN #traversalMethod_hasId_Object_Object | 'hasId' LPAREN traversalPredicate RPAREN #traversalMethod_hasId_P ; traversalMethod_hasKey : 'hasKey' LPAREN traversalPredicate RPAREN #traversalMethod_hasKey_P | 'hasKey' LPAREN stringLiteral (COMMA stringLiteralList)? RPAREN #traversalMethod_hasKey_String_String ; traversalMethod_hasLabel : 'hasLabel' LPAREN traversalPredicate RPAREN #traversalMethod_hasLabel_P | 'hasLabel' LPAREN stringLiteral (COMMA stringLiteralList)? RPAREN #traversalMethod_hasLabel_String_String ; traversalMethod_hasNot : 'hasNot' LPAREN stringLiteral RPAREN ; traversalMethod_hasValue : 'hasValue' LPAREN genericLiteral (COMMA genericLiteralList)? RPAREN #traversalMethod_hasValue_Object_Object | 'hasValue' LPAREN traversalPredicate RPAREN #traversalMethod_hasValue_P ; traversalMethod_id : 'id' LPAREN RPAREN ; traversalMethod_identity : 'identity' LPAREN RPAREN ; traversalMethod_in : 'in' LPAREN stringLiteralList RPAREN ; traversalMethod_inE : 'inE' LPAREN stringLiteralList RPAREN ; traversalMethod_inV : 'inV' LPAREN RPAREN ; traversalMethod_index : 'index' LPAREN RPAREN ; traversalMethod_inject : 'inject' LPAREN genericLiteralList RPAREN ; traversalMethod_is : 'is' LPAREN genericLiteral RPAREN #traversalMethod_is_Object | 'is' LPAREN traversalPredicate RPAREN #traversalMethod_is_P ; traversalMethod_key : 'key' LPAREN RPAREN ; traversalMethod_label : 'label' LPAREN RPAREN ; traversalMethod_limit : 'limit' LPAREN traversalScope COMMA integerLiteral RPAREN #traversalMethod_limit_Scope_long | 'limit' LPAREN integerLiteral RPAREN #traversalMethod_limit_long ; traversalMethod_local : 'local' LPAREN nestedTraversal RPAREN ; traversalMethod_loops : 'loops' LPAREN RPAREN #traversalMethod_loops_Empty | 'loops' LPAREN stringLiteral RPAREN #traversalMethod_loops_String ; traversalMethod_map : 'map' LPAREN nestedTraversal RPAREN ; traversalMethod_match : 'match' LPAREN nestedTraversalList RPAREN ; traversalMethod_math : 'math' LPAREN stringLiteral RPAREN ; traversalMethod_max : 'max' LPAREN RPAREN #traversalMethod_max_Empty | 'max' LPAREN traversalScope RPAREN #traversalMethod_max_Scope ; traversalMethod_mean : 'mean' LPAREN RPAREN #traversalMethod_mean_Empty | 'mean' LPAREN traversalScope RPAREN #traversalMethod_mean_Scope ; traversalMethod_min : 'min' LPAREN RPAREN #traversalMethod_min_Empty | 'min' LPAREN traversalScope RPAREN #traversalMethod_min_Scope ; traversalMethod_not : 'not' LPAREN nestedTraversal RPAREN ; traversalMethod_option : 'option' LPAREN traversalPredicate COMMA nestedTraversal RPAREN #traversalMethod_option_Predicate_Traversal | 'option' LPAREN traversalMerge COMMA (genericLiteralMap | nullLiteral) RPAREN #traversalMethod_option_Merge_Map | 'option' LPAREN traversalMerge COMMA nestedTraversal RPAREN #traversalMethod_option_Merge_Traversal | 'option' LPAREN genericLiteral COMMA nestedTraversal RPAREN #traversalMethod_option_Object_Traversal | 'option' LPAREN nestedTraversal RPAREN #traversalMethod_option_Traversal ; traversalMethod_optional : 'optional' LPAREN nestedTraversal RPAREN ; traversalMethod_or : 'or' LPAREN nestedTraversalList RPAREN ; traversalMethod_order : 'order' LPAREN RPAREN #traversalMethod_order_Empty | 'order' LPAREN traversalScope RPAREN #traversalMethod_order_Scope ; traversalMethod_otherV : 'otherV' LPAREN RPAREN ; traversalMethod_out : 'out' LPAREN stringLiteralList RPAREN ; traversalMethod_outE : 'outE' LPAREN stringLiteralList RPAREN ; traversalMethod_outV : 'outV' LPAREN RPAREN ; traversalMethod_pageRank : 'pageRank' LPAREN RPAREN #traversalMethod_pageRank_Empty | 'pageRank' LPAREN floatLiteral RPAREN #traversalMethod_pageRank_double ; traversalMethod_path : 'path' LPAREN RPAREN ; traversalMethod_peerPressure : 'peerPressure' LPAREN RPAREN ; traversalMethod_profile : 'profile' LPAREN RPAREN #traversalMethod_profile_Empty | 'profile' LPAREN stringLiteral RPAREN #traversalMethod_profile_String ; traversalMethod_project : 'project' LPAREN stringLiteral (COMMA stringLiteralList)? RPAREN ; traversalMethod_properties : 'properties' LPAREN stringLiteralList RPAREN ; traversalMethod_property : 'property' LPAREN traversalCardinality COMMA genericLiteral COMMA genericLiteral (COMMA genericLiteralList)? RPAREN #traversalMethod_property_Cardinality_Object_Object_Object | 'property' LPAREN genericLiteral COMMA genericLiteral (COMMA genericLiteralList)? RPAREN #traversalMethod_property_Object_Object_Object | 'property' LPAREN (genericLiteralMap | nullLiteral) RPAREN # traversalMethod_property_Object | 'property' LPAREN traversalCardinality COMMA (genericLiteralMap | nullLiteral) RPAREN # traversalMethod_property_Cardinality_Object ; traversalMethod_propertyMap : 'propertyMap' LPAREN stringLiteralList RPAREN ; traversalMethod_range : 'range' LPAREN traversalScope COMMA integerLiteral COMMA integerLiteral RPAREN #traversalMethod_range_Scope_long_long | 'range' LPAREN integerLiteral COMMA integerLiteral RPAREN #traversalMethod_range_long_long ; traversalMethod_read : 'read' LPAREN RPAREN ; traversalMethod_repeat : 'repeat' LPAREN stringLiteral COMMA nestedTraversal RPAREN #traversalMethod_repeat_String_Traversal | 'repeat' LPAREN nestedTraversal RPAREN #traversalMethod_repeat_Traversal ; traversalMethod_sack : 'sack' LPAREN traversalBiFunction RPAREN #traversalMethod_sack_BiFunction | 'sack' LPAREN RPAREN #traversalMethod_sack_Empty ; traversalMethod_sample : 'sample' LPAREN traversalScope COMMA integerLiteral RPAREN #traversalMethod_sample_Scope_int | 'sample' LPAREN integerLiteral RPAREN #traversalMethod_sample_int ; traversalMethod_select : 'select' LPAREN traversalColumn RPAREN #traversalMethod_select_Column | 'select' LPAREN traversalPop COMMA stringLiteral RPAREN #traversalMethod_select_Pop_String | 'select' LPAREN traversalPop COMMA stringLiteral COMMA stringLiteral (COMMA stringLiteralList)? RPAREN #traversalMethod_select_Pop_String_String_String | 'select' LPAREN traversalPop COMMA nestedTraversal RPAREN #traversalMethod_select_Pop_Traversal | 'select' LPAREN stringLiteral RPAREN #traversalMethod_select_String | 'select' LPAREN stringLiteral COMMA stringLiteral (COMMA stringLiteralList)? RPAREN #traversalMethod_select_String_String_String | 'select' LPAREN nestedTraversal RPAREN #traversalMethod_select_Traversal ; traversalMethod_shortestPath : 'shortestPath' LPAREN RPAREN ; traversalMethod_sideEffect : 'sideEffect' LPAREN nestedTraversal RPAREN ; traversalMethod_simplePath : 'simplePath' LPAREN RPAREN ; traversalMethod_skip : 'skip' LPAREN traversalScope COMMA integerLiteral RPAREN #traversalMethod_skip_Scope_long | 'skip' LPAREN integerLiteral RPAREN #traversalMethod_skip_long ; traversalMethod_store : 'store' LPAREN stringLiteral RPAREN ; traversalMethod_subgraph : 'subgraph' LPAREN stringLiteral RPAREN ; traversalMethod_sum : 'sum' LPAREN RPAREN #traversalMethod_sum_Empty | 'sum' LPAREN traversalScope RPAREN #traversalMethod_sum_Scope ; traversalMethod_tail : 'tail' LPAREN RPAREN #traversalMethod_tail_Empty | 'tail' LPAREN traversalScope RPAREN #traversalMethod_tail_Scope | 'tail' LPAREN traversalScope COMMA integerLiteral RPAREN #traversalMethod_tail_Scope_long | 'tail' LPAREN integerLiteral RPAREN #traversalMethod_tail_long ; traversalMethod_fail : 'fail' LPAREN RPAREN #traversalMethod_fail_Empty | 'fail' LPAREN stringLiteral RPAREN #traversalMethod_fail_String ; traversalMethod_timeLimit : 'timeLimit' LPAREN integerLiteral RPAREN ; traversalMethod_times : 'times' LPAREN integerLiteral RPAREN ; traversalMethod_to : 'to' LPAREN traversalDirection (COMMA stringLiteralList)? RPAREN #traversalMethod_to_Direction_String | 'to' LPAREN stringLiteral RPAREN #traversalMethod_to_String | 'to' LPAREN structureVertex RPAREN #traversalMethod_to_Vertex | 'to' LPAREN nestedTraversal RPAREN #traversalMethod_to_Traversal ; traversalMethod_toE : 'toE' LPAREN traversalDirection (COMMA stringLiteralList)? RPAREN ; traversalMethod_toV : 'toV' LPAREN traversalDirection RPAREN ; traversalMethod_tree : 'tree' LPAREN RPAREN #traversalMethod_tree_Empty | 'tree' LPAREN stringLiteral RPAREN #traversalMethod_tree_String ; traversalMethod_unfold : 'unfold' LPAREN RPAREN ; traversalMethod_union : 'union' LPAREN nestedTraversalList RPAREN ; traversalMethod_until : 'until' LPAREN traversalPredicate RPAREN #traversalMethod_until_Predicate | 'until' LPAREN nestedTraversal RPAREN #traversalMethod_until_Traversal ; traversalMethod_value : 'value' LPAREN RPAREN ; traversalMethod_valueMap : 'valueMap' LPAREN stringLiteralList RPAREN #traversalMethod_valueMap_String | 'valueMap' LPAREN booleanLiteral (COMMA stringLiteralList)? RPAREN #traversalMethod_valueMap_boolean_String ; traversalMethod_values : 'values' LPAREN stringLiteralList RPAREN ; traversalMethod_where : 'where' LPAREN traversalPredicate RPAREN #traversalMethod_where_P | 'where' LPAREN stringLiteral COMMA traversalPredicate RPAREN #traversalMethod_where_String_P | 'where' LPAREN nestedTraversal RPAREN #traversalMethod_where_Traversal ; traversalMethod_with : 'with' LPAREN stringLiteral RPAREN #traversalMethod_with_String | 'with' LPAREN stringLiteral COMMA genericLiteral RPAREN #traversalMethod_with_String_Object ; traversalMethod_write : 'write' LPAREN RPAREN ; traversalMethod_element : 'element' LPAREN RPAREN ; traversalMethod_call : 'call' LPAREN stringLiteral RPAREN #traversalMethod_call_string | 'call' LPAREN stringLiteral COMMA genericLiteralMap RPAREN #traversalMethod_call_string_map | 'call' LPAREN stringLiteral COMMA nestedTraversal RPAREN #traversalMethod_call_string_traversal | 'call' LPAREN stringLiteral COMMA genericLiteralMap COMMA nestedTraversal RPAREN #traversalMethod_call_string_map_traversal ; /********************************************* ARGUMENT AND TERMINAL RULES **********************************************/ // There is syntax available in the construction of a ReferenceVertex, that allows the label to not be specified. // That use case is related to OLAP when the StarGraph does not preserve the label of adjacent vertices or other // fail fast scenarios in that processing model. It is not relevant to the grammar however when a user is creating // the Vertex to be used in a Traversal and therefore both id and label are required. structureVertex : NEW ('Vertex'|'ReferenceVertex') LPAREN genericLiteral COMMA stringLiteral RPAREN ; traversalStrategy // : 'ConnectiveStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'ElementIdStrategy' - not supported as the configuration takes a lambda // | 'EventStrategy' - not supported as there is no way to send events back to the client // | 'HaltedTraverserStrategy' - not supported as it is not typically relevant to OLTP // | 'OptionsStrategy' - not supported as it's internal to with() : NEW 'PartitionStrategy' LPAREN traversalStrategyArgs_PartitionStrategy? (COMMA traversalStrategyArgs_PartitionStrategy)* RPAREN // | 'RequirementStrategy' - not supported as it's internally relevant only // | 'SackStrategy' - not supported directly as it's internal to withSack() | NEW 'SeedStrategy' LPAREN 'seed' COLON integerLiteral RPAREN // | 'SideEffectStrategy' - not supported directly as it's internal to withSideEffect() | NEW 'SubgraphStrategy' LPAREN traversalStrategyArgs_SubgraphStrategy? (COMMA traversalStrategyArgs_SubgraphStrategy)* RPAREN // | 'MatchAlgorithmStrategy' - not supported directly as it's internal to match() // | 'ProfileStrategy' - not supported directly as it's internal to profile() // | 'ReferenceElementStrategy' - not supported directly as users really can't/shouldn't change this in our context of a remote Gremlin provider // | 'AdjacentToIncidentStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'ByModulatorOptimizationStrategy' - not supported as it is a default strategy and we don't allow removal at this time | NEW? 'ProductiveByStrategy' (LPAREN traversalStrategyArgs_ProductiveByStrategy? RPAREN)? // | 'CountStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'EarlyLimitStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'FilterRankingStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'IdentityRemovalStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'IncidentToAdjacentStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'InlineFilterStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'LazyBarrierStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'MatchPredicateStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'OrderLimitStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'PathProcessorStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'PathRetractionStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'RepeatUnrollStrategy' - not supported as it is a default strategy and we don't allow removal at this time // | 'ComputerVerificationStrategy' - not supported since it's GraphComputer related | NEW 'EdgeLabelVerificationStrategy' LPAREN traversalStrategyArgs_EdgeLabelVerificationStrategy? (COMMA traversalStrategyArgs_EdgeLabelVerificationStrategy)* RPAREN // | 'LambdaRestrictionStrategy' - not supported as we don't support lambdas in any situation | 'ReadOnlyStrategy' | NEW 'ReservedKeysVerificationStrategy' LPAREN traversalStrategyArgs_ReservedKeysVerificationStrategy? (COMMA traversalStrategyArgs_ReservedKeysVerificationStrategy)* RPAREN // | 'StandardVerificationStrategy' - not supported since this is an interal strategy ; traversalStrategyArgs_ProductiveByStrategy : 'productiveKeys' COLON stringLiteralList ; traversalStrategyArgs_PartitionStrategy : 'includeMetaProperties' COLON booleanLiteral | 'writePartition' COLON stringLiteral | 'partitionKey' COLON stringLiteral | 'readPartitions' COLON stringLiteralList ; traversalStrategyArgs_SubgraphStrategy : 'vertices' COLON nestedTraversal | 'edges' COLON nestedTraversal | 'vertexProperties' COLON nestedTraversal | 'checkAdjacentVertices' COLON booleanLiteral ; traversalStrategyArgs_EdgeLabelVerificationStrategy : 'throwException' COLON booleanLiteral | 'logWarning' COLON booleanLiteral ; traversalStrategyArgs_ReservedKeysVerificationStrategy : 'keys' COLON stringLiteralList | 'throwException' COLON booleanLiteral | 'logWarning' COLON booleanLiteral ; traversalScope : 'local' | 'Scope.local' | 'global' | 'Scope.global' ; traversalToken : 'id' | 'T.id' | 'label' | 'T.label' | 'key' | 'T.key' | 'value' | 'T.value' ; traversalMerge : 'onCreate' | 'Merge.onCreate' | 'onMatch' | 'Merge.onMatch' ; traversalOrder : 'incr' | 'Order.incr' | 'decr' | 'Order.decr' | 'asc' | 'Order.asc' | 'desc' | 'Order.desc' | 'shuffle' | 'Order.shuffle' ; traversalDirection : 'IN' | 'Direction.IN' | 'Direction.from' | 'from' | 'OUT' | 'Direction.OUT' | 'Direction.to' | 'to' | 'BOTH' | 'Direction.BOTH' ; traversalCardinality : 'single' | 'Cardinality.single' | 'set' | 'Cardinality.set' | 'list' | 'Cardinality.list' ; traversalColumn : 'keys' | 'Column.keys' | 'values' | 'Column.values' ; traversalPop : 'first' | 'Pop.first' | 'last' | 'Pop.last' | 'all' | 'Pop.all' | 'mixed' | 'Pop.mixed' ; traversalOperator : 'addAll' | 'Operator.addAll' | 'and' | 'Operator.and' | 'assign' | 'Operator.assign' | 'div' | 'Operator.div' | 'max' | 'Operator.max' | 'min' | 'Operator.min' | 'minus' | 'Operator.minus' | 'mult' | 'Operator.mult' | 'or' | 'Operator.or' | 'sum' | 'Operator.sum' | 'sumLong' | 'Operator.sumLong' ; traversalPick : 'any' | 'Pick.any' | 'none' | 'Pick.none' ; traversalPredicate : traversalPredicate_eq | traversalPredicate_neq | traversalPredicate_lt | traversalPredicate_lte | traversalPredicate_gt | traversalPredicate_gte | traversalPredicate_inside | traversalPredicate_outside | traversalPredicate_between | traversalPredicate_within | traversalPredicate_without | traversalPredicate_not | traversalPredicate_startingWith | traversalPredicate_notStartingWith | traversalPredicate_endingWith | traversalPredicate_notEndingWith | traversalPredicate_containing | traversalPredicate_notContaining | traversalPredicate_regex | traversalPredicate_notRegex | traversalPredicate DOT 'and' LPAREN traversalPredicate RPAREN | traversalPredicate DOT 'or' LPAREN traversalPredicate RPAREN | traversalPredicate DOT 'negate' LPAREN RPAREN ; traversalTerminalMethod : traversalTerminalMethod_explain | traversalTerminalMethod_iterate | traversalTerminalMethod_hasNext | traversalTerminalMethod_tryNext | traversalTerminalMethod_next | traversalTerminalMethod_toList | traversalTerminalMethod_toSet | traversalTerminalMethod_toBulkSet ; traversalSackMethod : 'normSack' | 'Barrier.normSack' ; traversalSelfMethod : traversalSelfMethod_none ; // Additional special rules that are derived from above // These are used to restrict broad method signatures that accept lambdas // to a smaller set. traversalComparator : traversalOrder ; traversalFunction : traversalToken | traversalColumn ; traversalBiFunction : traversalOperator ; traversalPredicate_eq : ('P.eq' | 'eq') LPAREN genericLiteral RPAREN ; traversalPredicate_neq : ('P.neq' | 'neq') LPAREN genericLiteral RPAREN ; traversalPredicate_lt : ('P.lt' | 'lt') LPAREN genericLiteral RPAREN ; traversalPredicate_lte : ('P.lte' | 'lte') LPAREN genericLiteral RPAREN ; traversalPredicate_gt : ('P.gt' | 'gt') LPAREN genericLiteral RPAREN ; traversalPredicate_gte : ('P.gte' | 'gte') LPAREN genericLiteral RPAREN ; traversalPredicate_inside : ('P.inside' | 'inside') LPAREN genericLiteral COMMA genericLiteral RPAREN ; traversalPredicate_outside : ('P.outside' | 'outside') LPAREN genericLiteral COMMA genericLiteral RPAREN ; traversalPredicate_between : ('P.between' | 'between') LPAREN genericLiteral COMMA genericLiteral RPAREN ; traversalPredicate_within : ('P.within' | 'within') LPAREN RPAREN | ('P.within' | 'within') LPAREN genericLiteralList RPAREN ; traversalPredicate_without : ('P.without' | 'without') LPAREN RPAREN | ('P.without' | 'without') LPAREN genericLiteralList RPAREN ; traversalPredicate_not : ('P.not' | 'not') LPAREN traversalPredicate RPAREN ; traversalPredicate_containing : ('TextP.containing' | 'containing') LPAREN stringLiteral RPAREN ; traversalPredicate_notContaining : ('TextP.notContaining' | 'notContaining') LPAREN stringLiteral RPAREN ; traversalPredicate_startingWith : ('TextP.startingWith' | 'startingWith') LPAREN stringLiteral RPAREN ; traversalPredicate_notStartingWith : ('TextP.notStartingWith' | 'notStartingWith') LPAREN stringLiteral RPAREN ; traversalPredicate_endingWith : ('TextP.endingWith' | 'endingWith') LPAREN stringLiteral RPAREN ; traversalPredicate_notEndingWith : ('TextP.notEndingWith' | 'notEndingWith') LPAREN stringLiteral RPAREN ; traversalPredicate_regex : ('TextP.regex' | 'regex') LPAREN stringLiteral RPAREN ; traversalPredicate_notRegex : ('TextP.notRegex' | 'notRegex') LPAREN stringLiteral RPAREN ; traversalTerminalMethod_explain : 'explain' LPAREN RPAREN ; traversalTerminalMethod_hasNext : 'hasNext' LPAREN RPAREN ; traversalTerminalMethod_iterate : 'iterate' LPAREN RPAREN ; traversalTerminalMethod_tryNext : 'tryNext' LPAREN RPAREN ; traversalTerminalMethod_next : 'next' LPAREN RPAREN | 'next' LPAREN integerLiteral RPAREN ; traversalTerminalMethod_toList : 'toList' LPAREN RPAREN ; traversalTerminalMethod_toSet : 'toSet' LPAREN RPAREN ; traversalTerminalMethod_toBulkSet : 'toBulkSet' LPAREN RPAREN ; traversalSelfMethod_none : 'none' LPAREN RPAREN ; // Gremlin specific lexer rules gremlinStringConstants : withOptionsStringConstants | shortestPathStringConstants | connectedComponentConstants | pageRankStringConstants | peerPressureStringConstants | ioOptionsStringConstants ; connectedComponentConstants : gremlinStringConstants_connectedComponentStringConstants_component | gremlinStringConstants_connectedComponentStringConstants_edges | gremlinStringConstants_connectedComponentStringConstants_propertyName ; pageRankStringConstants : gremlinStringConstants_pageRankStringConstants_edges | gremlinStringConstants_pageRankStringConstants_times | gremlinStringConstants_pageRankStringConstants_propertyName ; peerPressureStringConstants : gremlinStringConstants_peerPressureStringConstants_edges | gremlinStringConstants_peerPressureStringConstants_times | gremlinStringConstants_peerPressureStringConstants_propertyName ; shortestPathStringConstants : gremlinStringConstants_shortestPathStringConstants_target | gremlinStringConstants_shortestPathStringConstants_edges | gremlinStringConstants_shortestPathStringConstants_distance | gremlinStringConstants_shortestPathStringConstants_maxDistance | gremlinStringConstants_shortestPathStringConstants_includeEdges ; withOptionsStringConstants : gremlinStringConstants_withOptionsStringConstants_tokens | gremlinStringConstants_withOptionsStringConstants_none | gremlinStringConstants_withOptionsStringConstants_ids | gremlinStringConstants_withOptionsStringConstants_labels | gremlinStringConstants_withOptionsStringConstants_keys | gremlinStringConstants_withOptionsStringConstants_values | gremlinStringConstants_withOptionsStringConstants_all | gremlinStringConstants_withOptionsStringConstants_indexer | gremlinStringConstants_withOptionsStringConstants_list | gremlinStringConstants_withOptionsStringConstants_map ; ioOptionsStringConstants : gremlinStringConstants_ioOptionsStringConstants_reader | gremlinStringConstants_ioOptionsStringConstants_writer | gremlinStringConstants_ioOptionsStringConstants_gryo | gremlinStringConstants_ioOptionsStringConstants_graphson | gremlinStringConstants_ioOptionsStringConstants_graphml ; gremlinStringConstants_connectedComponentStringConstants_component : connectedComponentStringConstant DOT 'component' ; gremlinStringConstants_connectedComponentStringConstants_edges : connectedComponentStringConstant DOT 'edges' ; gremlinStringConstants_connectedComponentStringConstants_propertyName : connectedComponentStringConstant DOT 'propertyName' ; gremlinStringConstants_pageRankStringConstants_edges : pageRankStringConstant DOT 'edges' ; gremlinStringConstants_pageRankStringConstants_times : pageRankStringConstant DOT 'times' ; gremlinStringConstants_pageRankStringConstants_propertyName : pageRankStringConstant DOT 'propertyName' ; gremlinStringConstants_peerPressureStringConstants_edges : peerPressureStringConstant DOT 'edges' ; gremlinStringConstants_peerPressureStringConstants_times : peerPressureStringConstant DOT 'times' ; gremlinStringConstants_peerPressureStringConstants_propertyName : peerPressureStringConstant DOT 'propertyName' ; gremlinStringConstants_shortestPathStringConstants_target : shortestPathStringConstant DOT 'target' ; gremlinStringConstants_shortestPathStringConstants_edges : shortestPathStringConstant DOT 'edges' ; gremlinStringConstants_shortestPathStringConstants_distance : shortestPathStringConstant DOT 'distance' ; gremlinStringConstants_shortestPathStringConstants_maxDistance : shortestPathStringConstant DOT 'maxDistance' ; gremlinStringConstants_shortestPathStringConstants_includeEdges : shortestPathStringConstant DOT 'includeEdges' ; gremlinStringConstants_withOptionsStringConstants_tokens : withOptionsStringConstant DOT 'tokens' ; gremlinStringConstants_withOptionsStringConstants_none : withOptionsStringConstant DOT 'none' ; gremlinStringConstants_withOptionsStringConstants_ids : withOptionsStringConstant DOT 'ids' ; gremlinStringConstants_withOptionsStringConstants_labels : withOptionsStringConstant DOT 'labels' ; gremlinStringConstants_withOptionsStringConstants_keys : withOptionsStringConstant DOT 'keys' ; gremlinStringConstants_withOptionsStringConstants_values : withOptionsStringConstant DOT 'values' ; gremlinStringConstants_withOptionsStringConstants_all : withOptionsStringConstant DOT 'all' ; gremlinStringConstants_withOptionsStringConstants_indexer : withOptionsStringConstant DOT 'indexer' ; gremlinStringConstants_withOptionsStringConstants_list : withOptionsStringConstant DOT 'list' ; gremlinStringConstants_withOptionsStringConstants_map : withOptionsStringConstant DOT 'map' ; gremlinStringConstants_ioOptionsStringConstants_reader : ioOptionsStringConstant DOT 'reader' ; gremlinStringConstants_ioOptionsStringConstants_writer : ioOptionsStringConstant DOT 'writer' ; gremlinStringConstants_ioOptionsStringConstants_gryo : ioOptionsStringConstant DOT 'gryo' ; gremlinStringConstants_ioOptionsStringConstants_graphson : ioOptionsStringConstant DOT 'graphson' ; gremlinStringConstants_ioOptionsStringConstants_graphml : ioOptionsStringConstant DOT 'graphml' ; connectedComponentStringConstant : 'ConnectedComponent' ; pageRankStringConstant : 'PageRank' ; peerPressureStringConstant : 'PeerPressure' ; shortestPathStringConstant : 'ShortestPath' ; withOptionsStringConstant : 'WithOptions' ; ioOptionsStringConstant : 'IO' ; traversalStrategyList : traversalStrategyExpr? ; traversalStrategyExpr : traversalStrategy (COMMA traversalStrategy)* ; nestedTraversalList : nestedTraversalExpr? ; nestedTraversalExpr : nestedTraversal (COMMA nestedTraversal)* ; genericLiteralList : genericLiteralExpr? ; genericLiteralExpr : genericLiteral (COMMA genericLiteral)* ; genericLiteralRange : integerLiteral DOT DOT integerLiteral | stringLiteral DOT DOT stringLiteral ; genericLiteralCollection : LBRACK (genericLiteral (COMMA genericLiteral)*)? RBRACK ; stringLiteralList : stringLiteralExpr? | LBRACK stringLiteralExpr? RBRACK ; stringLiteralExpr : stringLiteral (COMMA stringLiteral)* ; genericLiteral : integerLiteral | floatLiteral | booleanLiteral | stringLiteral | dateLiteral | nullLiteral | nanLiteral | infLiteral // Allow the generic literal to match specific gremlin tokens also | traversalToken | traversalCardinality | traversalDirection | traversalPick | structureVertex | genericLiteralCollection | genericLiteralRange | nestedTraversal | terminatedTraversal | genericLiteralMap ; genericLiteralMap : LBRACK (genericLiteral)? COLON (genericLiteral)? (COMMA (genericLiteral)? COLON (genericLiteral)?)* RBRACK ; integerLiteral : IntegerLiteral ; floatLiteral : FloatingPointLiteral ; booleanLiteral : BooleanLiteral ; stringLiteral : NonEmptyStringLiteral | EmptyStringLiteral | NullLiteral | gremlinStringConstants ; dateLiteral : 'datetime' LPAREN stringLiteral RPAREN ; nullLiteral : NullLiteral ; nanLiteral : NaNLiteral ; infLiteral : SignedInfLiteral ; /********************************************* LEXER RULES **********************************************/ // Lexer rules // These rules are extracted from Java ANTLRv4 Grammar. // Source: https://github.com/antlr/grammars-v4/blob/master/java8/Java8.g4 // §3.9 Keywords NEW : 'new'; // Integer Literals IntegerLiteral : Sign? DecimalIntegerLiteral | Sign? HexIntegerLiteral | Sign? OctalIntegerLiteral ; fragment DecimalIntegerLiteral : DecimalNumeral IntegerTypeSuffix? ; fragment HexIntegerLiteral : HexNumeral IntegerTypeSuffix? ; fragment OctalIntegerLiteral : OctalNumeral IntegerTypeSuffix? ; fragment IntegerTypeSuffix : [bBsSnNiIlL] ; fragment DecimalNumeral : '0' | NonZeroDigit (Digits? | Underscores Digits) ; fragment Digits : Digit (DigitsAndUnderscores? Digit)? ; fragment Digit : '0' | NonZeroDigit ; fragment NonZeroDigit : [1-9] ; fragment DigitsAndUnderscores : DigitOrUnderscore+ ; fragment DigitOrUnderscore : Digit | '_' ; fragment Underscores : '_'+ ; fragment HexNumeral : '0' [xX] HexDigits ; fragment HexDigits : HexDigit (HexDigitsAndUnderscores? HexDigit)? ; fragment HexDigit : [0-9a-fA-F] ; fragment HexDigitsAndUnderscores : HexDigitOrUnderscore+ ; fragment HexDigitOrUnderscore : HexDigit | '_' ; fragment OctalNumeral : '0' Underscores? OctalDigits ; fragment OctalDigits : OctalDigit (OctalDigitsAndUnderscores? OctalDigit)? ; fragment OctalDigit : [0-7] ; fragment OctalDigitsAndUnderscores : OctalDigitOrUnderscore+ ; fragment OctalDigitOrUnderscore : OctalDigit | '_' ; // Floating-Point Literals FloatingPointLiteral : Sign? DecimalFloatingPointLiteral ; fragment DecimalFloatingPointLiteral : Digits ('.' Digits ExponentPart? | ExponentPart) FloatTypeSuffix? | Digits FloatTypeSuffix ; fragment ExponentPart : ExponentIndicator SignedInteger ; fragment ExponentIndicator : [eE] ; fragment SignedInteger : Sign? Digits ; fragment Sign : [+-] ; fragment FloatTypeSuffix : [fFdDmM] ; // Boolean Literals BooleanLiteral : 'true' | 'false' ; // Null Literal NullLiteral : 'null' ; // NaN Literal NaNLiteral : 'NaN' ; // Inf Literal SignedInfLiteral : Sign? InfLiteral ; InfLiteral : 'Infinity' ; // String Literals // String literal is customized since Java only allows double quoted strings where Groovy supports single quoted // literals also. A side effect of this is ANTLR will not be able to parse single character string literals with // single quoted so we instead remove char literal altogether and only have string literal in lexer tokens. NonEmptyStringLiteral : '""' DoubleQuotedStringCharacters '""' | '\\'' SingleQuotedStringCharacters '\\'' ; // We define NonEmptyStringLiteral and EmptyStringLiteral separately so that we can unambiguously handle empty queries EmptyStringLiteral : '""""' | '\\'\\'' ; fragment DoubleQuotedStringCharacters : DoubleQuotedStringCharacter+ ; fragment DoubleQuotedStringCharacter : ~('""' | '\\\\') | JoinLineEscape | EscapeSequence ; fragment SingleQuotedStringCharacters : SingleQuotedStringCharacter+ ; fragment SingleQuotedStringCharacter : ~('\\'' | '\\\\') | JoinLineEscape | EscapeSequence ; // Escape Sequences for Character and String Literals fragment JoinLineEscape : '\\\\' '\\r'? '\\n' ; fragment EscapeSequence : '\\\\' [btnfr""'\\\\] | OctalEscape | UnicodeEscape // This is not in the spec but prevents having to preprocess the input ; fragment OctalEscape : '\\\\' OctalDigit | '\\\\' OctalDigit OctalDigit | '\\\\' ZeroToThree OctalDigit OctalDigit ; fragment ZeroToThree : [0-3] ; // This is not in the spec but prevents having to preprocess the input fragment UnicodeEscape : '\\\\' 'u'+ HexDigit HexDigit HexDigit HexDigit ; // Separators LPAREN : '('; RPAREN : ')'; LBRACE : '{'; RBRACE : '}'; LBRACK : '['; RBRACK : ']'; SEMI : ';'; COMMA : ','; DOT : '.'; COLON : ':'; TRAVERSAL_ROOT: 'g'; ANON_TRAVERSAL_ROOT: '__'; // Trim whitespace and comments if present WS : [ \\t\\r\\n\\u000C]+ -> skip ; LINE_COMMENT : '//' ~[\\r\\n]* -> skip ; ",12162,False,2204.552005543204,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, ANSI SQL parsing mode is enabled. */ public boolean ansi = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE db=errorCapturingIdentifier #use | CREATE database (IF NOT EXISTS)? db=errorCapturingIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH DBPROPERTIES tablePropertyList))* #createDatabase | ALTER database db=errorCapturingIdentifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | ALTER database db=errorCapturingIdentifier SET locationSpec #setDatabaseLocation | DROP database (IF EXISTS)? db=errorCapturingIdentifier (RESTRICT | CASCADE)? #dropDatabase | SHOW DATABASES (LIKE? pattern=STRING)? #showDatabases | SHOW NAMESPACES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE tableIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE multipartIdentifier RENAME COLUMN from=qualifiedName TO to=identifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=qualifiedNameList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=qualifiedNameList #dropTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE multipartIdentifier (ALTER | CHANGE) COLUMN? qualifiedName (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE tableIdentifier partitionSpec? CHANGE COLUMN? colName=errorCapturingIdentifier colType colPosition? #changeColumn | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER TABLE tableIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER VIEW tableIdentifier ADD (IF NOT EXISTS)? partitionSpec+ #addTablePartition | ALTER TABLE tableIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER TABLE tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER VIEW tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* #dropTablePartitions | ALTER TABLE multipartIdentifier SET locationSpec #setTableLocation | ALTER TABLE tableIdentifier partitionSpec SET locationSpec #setPartitionLocation | ALTER TABLE tableIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW tableIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? qualifiedName AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? qualifiedName #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=errorCapturingIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) tableIdentifier ((FROM | IN) db=errorCapturingIdentifier)? #showColumns | SHOW PARTITIONS tableIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (qualifiedName | pattern=STRING))? #showFunctions | SHOW CREATE TABLE tableIdentifier #showCreateTable | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) database EXTENDED? db=errorCapturingIdentifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE tableIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE tableIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? tableIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE tableIdentifier partitionSpec? #loadData | TRUNCATE TABLE tableIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE tableIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING qualifiedName ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assign (',' assign)* ; assign : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | IDENTIFIER '->' expression #lambda | '(' IDENTIFIER (',' IDENTIFIER)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : {ansi}? INTERVAL? intervalField+ | {!ansi}? INTERVAL intervalField* ; intervalField : value=intervalValue unit=intervalUnit (TO to=intervalUnit)? ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER qualifiedName ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=qualifiedName dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!ansi}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {ansi}? ansiNonReserved #unquotedIdentifier | {!ansi}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `spark.sql.parser.ansi.enabled=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `spark.sql.parser.ansi.enabled=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `spark.sql.parser.ansi.enabled=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12043,False,2236.426147844548,median "function __doPanZoom(_1,_2,_3,_4){ var _5=null; try{ _5=eval(_1); } catch(ex){ } if(_5==null){ return; } var _6=__getMapTools(_2); if(_6==null){ return; } var _7=_6.GetZoom(); switch(_3){ case ""ZoomFull"": _5.updateThumb(0); break; case ""ZoomIn"": _5.updateThumb(_7+1); break; case ""ZoomOut"": _5.updateThumb(_7-1); break; case ""SetZoom"": _5.updateThumb(_4); break; } _6[_3](_4); } function __UpdateAnimationLayer(_8,_9){ __amUpdateEventValidation(); if(!__amIsAspAjaxCall){ try{ var _a=_8.split(""``""); if(_a[0]==""LAYER""){ var _b=__$(_9+""_animdiv""); __clearDiv(_b); _b.innerHTML=_a[2]; __$(_9+""_animarg"").value=_a[1]; }else{ var _c=__$(_9); __clearDiv(_c); _c.innerHTML=_a[1]; var _d=__getMapTools(_9); if(_d){ _d.UpdateBackLayer(); } } } catch(e){ } } var _d=__getMapTools(_9); if(!_d){ return; } if(_d.GetEnableAnimation()){ _d.RunAnimationTimer(); } } function __UpdateAnimationLayerError(_e,_f){ __amUpdateEventValidation(); var map=__getMapTools(_f); if(!map){ return; } if(map.GetEnableAnimation()){ map.RunAnimationTimer(); } } function __AspMapTools(){ this.ZOOMFULL=100; this.PIXELPAN=101; this.ZOOMIN=102; this.ZOOMOUT=103; this.SETZOOM=104; this.CENTERAT=105; this.SETSCALE=106; this.CENTERANDZOOM=107; this.CENTERANDSCALE=108; this.RESIZETO=109; this.mouseMoveHandler=null; this.panToolHandler=null; this.pointToolHandler=null; this.infoToolHandler=null; this.markerClickHandler=null; this.apiVar=null; this.Add_MouseMove=function(_11){ this.mouseMoveHandler=_11; }; this.Remove_MouseMove=function(_12){ this.mouseMoveHandler=null; }; this.Add_PanToolClick=function(_13){ this.panToolHandler=_13; }; this.Remove_PanToolClick=function(_14){ this.panToolHandler=null; }; this.Add_PointTool=function(_15){ this.pointToolHandler=_15; }; this.Remove_PointTool=function(_16){ this.pointToolHandler=null; }; this.Add_InfoTool=function(_17){ this.infoToolHandler=_17; }; this.Remove_InfoTool=function(_18){ this.infoToolHandler=null; }; this.Add_MarkerClick=function(_19){ this.markerClickHandler=_19; }; this.Remove_MarkerClick=function(_1a){ this.markerClickHandler=null; }; this.PanLeft=function(_1b){ this.Pan(-this.MapWidth()*_1b/100,0); }; this.PanTop=function(_1c){ this.Pan(0,-this.MapHeight()*_1c/100); }; this.PanRight=function(_1d){ this.Pan(this.MapWidth()*_1d/100,0); }; this.PanBottom=function(_1e){ this.Pan(0,this.MapHeight()*_1e/100); }; this.ZoomFull=function(){ this.ApiCall(this.ZOOMFULL); }; this.ZoomIn=function(){ this.ApiCall(this.ZOOMIN); }; this.ZoomOut=function(){ this.ApiCall(this.ZOOMOUT); }; this.Pan=function(dx,dy){ this.ApiCallXY(this.PIXELPAN,"""",dx,dy); }; this.Refresh=function(){ this.Pan(0,0); }; this.CenterAt=function(x,y){ this.ApiCallXY(this.CENTERAT,"""",x,y); }; this.CenterAndZoom=function(x,y,_25){ this.ApiCallXY(this.CENTERANDZOOM,_25,x,y); }; this.CenterAndScale=function(x,y,_28){ this.ApiCallXY(this.CENTERANDSCALE,_28,x,y); }; this.ResizeTo=function(_29,_2a){ if(this.MapWidth()!=_29||this.MapHeight()!=_2a){ this.ApiCallXY(this.RESIZETO,"""",_29,_2a); } }; this.Resize=function(){ var d=__$(this.MapID); if(d.parentNode){ this.ResizeTo(__getDivW(d.parentNode),__getDivH(d.parentNode)); } }; this.SetZoom=function(_2c){ if(this.GetZoom()!=_2c){ this.ApiCall(this.SETZOOM,_2c); } }; this.GetZoom=function(){ return this.GetInt(""zoom""); }; this.GetZoomLevelCount=function(){ return this.GetInt(""zlct""); }; this.GetMapScale=function(){ return this.GetDbl(""scl""); }; this.SetMapScale=function(_2d){ this.ApiCall(this.SETSCALE,_2d); }; this.ApiCall=function(cmd,arg){ this.ApiCallXY(cmd,arg,"""",""""); }; this.ApiCallXY=function(cmd,arg,x,y){ if(typeof (arg)==""undefined""){ arg=""""; } this.SetApiCall(); this.SubmitTool(cmd,x,y,arg); }; this.ttimer=null; this.OnLoad=function(){ if(this.ttimer==null&&this.GetEnableAnimation()){ this.RunAnimationTimer(); } }; this.RunAnimationTimer=function(){ if(this.GetAnimationInterval()>0){ clearTimeout(this.ttimer); this.ttimer=null; this.ttimer=setTimeout(__getMapToolsName(this.MapID)+"".DoAnimation()"",this.GetAnimationInterval()); } }; this.DoAnimation=function(){ if(!__amIsAspAjaxCall){ map_callback(this.UniqueID,__UpdateAnimationLayer,""ANIM"",this.MapID,__UpdateAnimationLayerError); }else{ this.RunAnimationTimer(); } }; this.RefreshAnimationLayer=function(){ if(!this.GetEnableAnimation()){ this.DoAnimation(); } return false; }; this.SetAnimationInterval=function(_34){ this.SetInt(""animint"",_34); }; this.GetAnimationInterval=function(){ return this.GetInt(""animint""); }; this.GetEnableAnimation=function(){ return this.GetBool(""at""); }; this.SetEnableAnimation=function(_35){ if(_35!=this.GetEnableAnimation()){ this.SetBool(""at"",_35); if(_35){ this.DoAnimation(); }else{ clearTimeout(this.ttimer); this.ttimer=null; } } return false; }; this.hspc=0; this.vspc=0; this.MapCanvas=null; this.MapID=""""; this.UniqueID=""""; this.ZoomBarVar=null; this.GetZoomBar=function(){ try{ return eval(this.ZoomBarVar); } catch(ex){ } return null; }; this.TOOL_ZOOMIN=1; this.TOOL_ZOOMOUT=2; this.TOOL_CENTER=3; this.TOOL_PAN=4; this.TOOL_INFO=5; this.TOOL_DISTANCE=6; this.TOOL_QINFO=7; this.TOOL_POINT=8; this.TOOL_LINE=9; this.TOOL_POLYLINE=10; this.TOOL_RECT=11; this.TOOL_CIRCLE=12; this.TOOL_POLYGON=13; this.isDragging=false; this.x1=0; this.y1=0; this.x2=0; this.y2=0; this.prevPanX=0; this.prevPanY=0; this.Xpts=null; this.Ypts=null; this.rleft=0; this.rright=0; this.rtop=0; this.rbottom=0; this.isOnMoveInited=false; this.qInfoX=0; this.qInfoY=0; this.SetTool=function(_36){ this.CancelTool(); this.SetMapTool(_36); this.UpdateCursor(); }; this.SetArgument=function(arg){ this.SetToolArgument(arg); }; this.GetArgument=function(){ return this.GetToolArgument(); }; this.GetTool=function(){ return this.GetMapTool(); }; this.UpdateCursor=function(){ this.SetCursor(this.GetCursor()); }; this.StartTool=function(x,y){ this.MapCanvas.setStroke(this.LineWidth()); this.MapCanvas.setColor(this.LineColor()); switch(this.GetTool()){ case this.TOOL_POINT: this.StartPoint(x,y); break; case this.TOOL_ZOOMIN: case this.TOOL_RECT: this.StartRect(x,y); break; case this.TOOL_LINE: this.StartLine(x,y); break; case this.TOOL_PAN: this.StartPan(x,y); break; case this.TOOL_CIRCLE: this.StartPolyline(x,y); this.StartCircle(x,y); break; case this.TOOL_DISTANCE: case this.TOOL_POLYLINE: this.StartPolyline(x,y); break; case this.TOOL_POLYGON: this.StartPolygon(x,y); break; case this.TOOL_ZOOMOUT: this.StartZoomOut(x,y); break; case this.TOOL_CENTER: this.StartCenter(x,y); break; case this.TOOL_INFO: this.StartInfo(x,y); break; case this.TOOL_QINFO: this.StartQuickInfo(x,y); break; } }; this.DragTool=function(x,y){ switch(this.GetTool()){ case this.TOOL_RECT: case this.TOOL_ZOOMIN: this.DrawRect(x,y); break; case this.TOOL_LINE: this.DrawLine(x,y); break; case this.TOOL_PAN: this.DrawPan(x,y); break; case this.TOOL_CIRCLE: this.DrawDistance(x,y,false); this.DrawCircle(x,y,false); break; case this.TOOL_POLYLINE: this.DrawPolyline(x,y); break; case this.TOOL_DISTANCE: this.DrawDistance(x,y,true); break; case this.TOOL_POLYGON: this.DrawPolygon(x,y); break; case this.TOOL_INFO: this.DrawInfo(x,y); break; case this.TOOL_QINFO: this.DrawInfo(x,y); break; } }; this.StopTool=function(x,y){ switch(this.GetTool()){ case this.TOOL_RECT: this.StopRect(); break; case this.TOOL_LINE: this.StopLine(); break; case this.TOOL_PAN: this.StopPan(); break; case this.TOOL_CIRCLE: this.StopCircle(); this.StopDistance(); break; case this.TOOL_ZOOMIN: this.StopZoomIn(); break; case this.TOOL_INFO: this.StopInfo(); break; case this.TOOL_QINFO: this.StopQuickInfo(); break; } }; this.CancelTool=function(){ this.StopDrag(); this.MapCanvas.clear(); }; this.StopCompTool=function(){ switch(this.GetTool()){ case this.TOOL_POLYLINE: this.StopPolyline(); break; case this.TOOL_DISTANCE: this.StopDistance(); break; case this.TOOL_POLYGON: this.StopPolygon(); break; } }; this.StartPoint=function(x,y){ this.MapCanvas.clear(); this.OnPointTool(x,y); }; this.StartZoomOut=function(x,y){ this.MapCanvas.clear(); this.OnZoomOutTool(x,y); }; this.StartCenter=function(x,y){ this.MapCanvas.clear(); this.OnCenterTool(x,y); }; this.StartInfo=function(x,y){ this.MapCanvas.clear(); if(this.EnablePan()){ this.StartPan(x,y); }else{ this.OnInfoTool(x,y); } }; this.StartQuickInfo=function(x,y){ this.HideInfoWindow(); this.MapCanvas.clear(); if(this.EnablePan()){ this.StartPan(x,y); }else{ this.OnQuickInfoTool(x,y); } }; this.DrawInfo=function(x,y){ this.UpdateDrag(x,y); if(Math.abs(this.x1-this.x2)>1||Math.abs(this.y1-this.y2)>1){ this.DrawPan(x,y); } }; this.StopInfo=function(){ this.StopDrag(); if(Math.abs(this.x1-this.x2)>1||Math.abs(this.y1-this.y2)>1){ this.SetOverrideTool(this.TOOL_PAN); this.StopPan(); }else{ this.OnInfoTool(this.x1,this.y1); } }; this.StopQuickInfo=function(){ this.StopDrag(); if(Math.abs(this.x1-this.x2)>1||Math.abs(this.y1-this.y2)>1){ this.SetOverrideTool(this.TOOL_PAN); this.StopPan(); }else{ this.OnQuickInfoTool(this.x1,this.y1); } }; this.StopZoomIn=function(){ this.StopDrag(); this.MapCanvas.clear(); this.UpdateRect(); if(this.rright-this.rleft>1){ this.OnZoomInRectTool(this.rleft,this.rtop,this.rright,this.rbottom); }else{ this.OnZoomInTool(this.x1,this.y1); } }; this.StartRect=function(x,y){ this.StartDrag(x,y); this.UpdateRect(); }; this.DrawRect=function(x,y){ this.MapCanvas.clear(); this.UpdateDrag(x,y); this.UpdateRect(); this.MapCanvas.drawRect(this.rleft,this.rtop,this.rright-this.rleft,this.rbottom-this.rtop); this.MapCanvas.paint(); }; this.StopRect=function(){ this.StopDrag(); this.MapCanvas.clear(); this.UpdateRect(); if(this.rright-this.rleft>1){ this.OnRectTool(this.rleft,this.rtop,this.rright,this.rbottom); } }; this.UpdateRect=function(){ var _4e=this.x1; var _4f=this.y1; if(this.x1>this.x2){ this.rright=this.x1; this.rleft=this.x2; }else{ this.rleft=this.x1; this.rright=this.x2; } if(this.y1>this.y2){ this.rbottom=this.y1; this.rtop=this.y2; }else{ this.rtop=this.y1; this.rbottom=this.y2; } }; this.StartLine=function(x,y){ this.StartDrag(x,y); }; this.DrawLine=function(x,y){ this.MapCanvas.clear(); this.UpdateDrag(x,y); this.MapCanvas.drawLine(this.x1,this.y1,this.x2,this.y2); this.MapCanvas.paint(); }; this.StopLine=function(){ this.StopDrag(); this.MapCanvas.clear(); if(Math.abs(this.x1-this.x2)>1||Math.abs(this.y1-this.y2)>1){ this.OnLineTool(this.x1,this.y1,this.x2,this.y2); } }; this.StartPan=function(x,y){ this.HideInfoWindow(); this.StartDrag(x,y); this.prevPanX=x; this.prevPanY=y; }; this.DrawPan=function(x,y){ this.SetPanCursorForInfo(); this.UpdateDrag(x,y); try{ var img=__$(this.MapID+""_Image""); var _59=(this.x2-this.x1)+""px""; var top=(this.y2-this.y1)+""px""; img.style.left=_59; img.style.top=top; var _5b=0; while(true){ img=__$(this.MapID+""wms""+_5b); if(!img){ break; } img.style.left=_59; img.style.top=top; _5b++; } _59=(this.x2-this.x1); top=(this.y2-this.y1); this.PanImage(this.MapID+""tile"",_59,top); this.PanBackLayer(x-this.prevPanX,y-this.prevPanY); this.PanImage(this.MapID+""m"",_59,top); } catch(e){ } this.prevPanX=x; this.prevPanY=y; }; this.PanImage=function(id,_5d,top){ var _5f=0; while(true){ img=__$(id+_5f); if(!img){ break; } var _60=img.offsetTop; var _61=img.offsetLeft; if(!img.getAttribute(""itop"")){ img.setAttribute(""itop"",img.offsetTop); img.setAttribute(""ileft"",img.offsetLeft); }else{ _60=parseInt(img.getAttribute(""itop"")); _61=parseInt(img.getAttribute(""ileft"")); } img.style.left=(_61+_5d)+""px""; img.style.top=(_60+top)+""px""; _5f++; } }; this.StopPan=function(){ this.UpdateCursor(); this.StopDrag(); if(Math.abs(this.x1-this.x2)>1||Math.abs(this.y1-this.y2)>1){ this.OnLineTool(this.x1,this.y1,this.x2,this.y2); }else{ if(this.panToolHandler){ try{ this.panToolHandler(this.apiVar,this.GetMouseEventArgs(true)); } catch(e){ } } } }; this.StartCircle=function(x,y){ this.StartDrag(x,y); }; this.DrawCircle=function(x,y,_66){ if(_66){ this.MapCanvas.clear(); } this.UpdateDrag(x,y); var d=this.dist(this.x1,this.y1,this.x2,this.y2); this.MapCanvas.drawEllipse(this.x1-d,this.y1-d,d*2,d*2); this.MapCanvas.paint(); }; this.StopCircle=function(){ this.StopDrag(); this.MapCanvas.clear(); if(Math.abs(this.x1-this.x2)>1){ var d=this.dist(this.x1,this.y1,this.x2,this.y2); this.OnCircleTool(this.x1,this.y1,d); } }; this.dist=function(x1,y1,x2,y2){ return Math.round(Math.abs(this.hypot(x1-x2,y1-y2))); }; this.hypot=function(a,b){ return Math.sqrt((a*a)+(b*b)); }; this.StartPolyline=function(x,y){ if(!this.isDragging){ this.Xpts=new Array(); this.Ypts=new Array(); } this.StartDrag(x,y); this.Xpts[this.Xpts.length]=x; this.Ypts[this.Ypts.length]=y; }; this.DrawPolyline=function(x,y){ this.MapCanvas.clear(); this.UpdateDrag(x,y); this.MapCanvas.drawPolyline(this.Xpts,this.Ypts); this.MapCanvas.drawLine(this.x1,this.y1,this.x2,this.y2); this.MapCanvas.paint(); }; this.StopPolyline=function(){ this.StopDrag(); this.MapCanvas.clear(); if(this.Xpts.length>1&&this.dist(this.Xpts[0],this.Ypts[0],this.Xpts[1],this.Ypts[1])>1){ this.OnPolylineTool(this.Xpts,this.Ypts); } }; this.DrawDistance=function(x,y,_75){ var _76=""#000000""; var _77=""#FFFFFF""; this.MapCanvas.clear(); this.UpdateDrag(x,y); this.MapCanvas.drawPolyline(this.Xpts,this.Ypts); this.MapCanvas.drawLine(this.x1,this.y1,this.x2,this.y2); var _78=0; for(var i=0;i1){ var _7b=Math.round(1000*_78/1609.34)/1000; this.MapCanvas.drawString(_7b+"" ""+this.miles(),1,top,_76,_77); }else{ _7b=Math.round(_78/0.3048); this.MapCanvas.drawString(_7b+"" ""+this.feet(),1,top,_76,_77); } if((_78/1000)>1){ _7b=Math.round(1000*_78/1000)/1000; this.MapCanvas.drawString(_7b+"" ""+this.km(),1,top+14,_76,_77); }else{ this.MapCanvas.drawString((Math.round(10*_78)/10)+"" ""+this.meters(),1,top+14,_76,_77); } if(_75){ this.MapCanvas.paint(); } }; this.StopDistance=function(){ this.StopDrag(); this.MapCanvas.clear(); }; this.StartPolygon=function(x,y){ if(!this.isDragging){ this.Xpts=new Array(); this.Ypts=new Array(); } this.StartDrag(x,y); this.Xpts[this.Xpts.length]=x; this.Ypts[this.Ypts.length]=y; }; this.DrawPolygon=function(x,y){ this.MapCanvas.clear(); this.UpdateDrag(x,y); var tx=new Array().concat(this.Xpts); var ty=new Array().concat(this.Ypts); tx[tx.length]=this.x2; ty[ty.length]=this.y2; this.MapCanvas.drawPolygon(tx,ty); this.MapCanvas.paint(); }; this.StopPolygon=function(){ this.StopDrag(); this.MapCanvas.clear(); if(this.Xpts.length>2&&this.dist(this.Xpts[0],this.Ypts[0],this.Xpts[1],this.Ypts[1])>1){ this.Xpts[this.Xpts.length]=this.Xpts[0]; this.Ypts[this.Ypts.length]=this.Ypts[0]; this.OnPolygonTool(this.Xpts,this.Ypts); } }; this.StartDrag=function(x,y){ this.x1=x; this.y1=y; this.x2=this.x1+1; this.y2=this.y1+1; this.isDragging=true; }; this.UpdateDrag=function(x,y){ this.x2=x; this.y2=y; }; this.StopDrag=function(){ this.isDragging=false; return true; }; this.mouseX=0; this.mouseY=0; this.IsLeftDown=function(e){ var _87; if(e.which==null){ _87=(e.button<2)?1:((e.button==4)?2:3); }else{ _87=(e.which<2)?1:((e.which==2)?2:3); } return (_87==1); }; this.OnMouseDown=function(e){ if(!this.IsLeftDown(e)){ this.CancelTool(); return; } this.OnResize(); this.GetImageXY(e); if(this.mouseX>=0&&this.mouseX=0&&this.mouseYW){ t.mouseX=W-1; } if(t.mouseY>H){ t.mouseY=H-1; } if(t.mouseX<=0){ t.mouseX=1; } if(t.mouseY<=0){ t.mouseY=1; } if(t.isDragging){ t.DragTool(t.mouseX,t.mouseY); } return false; } var _8d; var _8e; var _8f=0; var _8a=null; this.OnMouseMove=function(e){ _8a=this; if(!this.isDragging){ this.RefreshCursor(); this.OnResize(); } this.GetImageXY(e); if(this.isDragging){ clearTimeout(_8d); _8f++; _8e=function(){ CallOnMouseMove(); }; if(_8f<=3){ _8d=setTimeout(_8e,80); }else{ _8e(); _8f=0; } } this.ShowLatLong(true); this.HideToolTips(); return false; }; this.RefreshCursor=function(){ var _91=__$(this.MapID+""_rf""); if(_91==null){ return; } if(_91.value==""1""){ this.UpdateCursor(); _91.value=""0""; } }; this.OnMouseLeave=function(e){ if(this.isDragging&&this.GetMapTool()==this.TOOL_PAN){ this.StopTool(); } this.ShowLatLong(false); return false; }; this.GetCenterLatLong=function(){ return new AspMap.Point(this.GetDbl(""_xd""),this.GetDbl(""_yd"")); }; this.GetCenterInMapUnits=function(){ return new AspMap.Point(this.GetDbl(""_xu""),this.GetDbl(""_yu"")); }; this.GetMouseEventArgs=function(_93){ var dpp=this.GetDbl(""_dpp""); var upp=this.GetDbl(""_upp""); var _96=this.GetCenterLatLong(); var lng=_96.x+(this.mouseX-Math.round(this.MapWidth()/2))*dpp; var lat=_96.y-(this.mouseY-Math.round(this.MapHeight()/2))*dpp; _96=this.GetCenterInMapUnits(); var x=_96.x+(this.mouseX-Math.round(this.MapWidth()/2))*upp; var y=_96.y-(this.mouseY-Math.round(this.MapHeight()/2))*upp; var _9b=new AspMap.MouseEventArgs(); _9b.x=this.mouseX; _9b.y=this.mouseY; _9b.isInside=_93; _9b.longitude=lng; _9b.latitude=lat; _9b.mapPoint=new AspMap.Point(x,y); return _9b; }; this.ShowLatLong=function(_9c){ try{ if(this.mouseMoveHandler){ this.mouseMoveHandler(this.apiVar,this.GetMouseEventArgs(_9c)); } } catch(ex){ } }; this.OnMouseOver=function(e){ this.RefreshCursor(); return false; }; this.OnMouseUp=function(e){ if(this.isDragging){ this.GetImageXY(e); this.StopTool(this.mouseX,this.mouseY); } return false; }; this.OnDoubleClick=function(e){ var _a0=this.GetTool(); if(this.isDragging){ this.StopCompTool(); }else{ if(_a0==this.TOOL_PAN||_a0==this.TOOL_INFO||_a0==this.TOOL_QINFO){ if(!this.IsLeftDown(e)){ return; } this.OnResize(); this.GetImageXY(e); this.SetOverrideTool(this.TOOL_ZOOMIN); this.OnZoomInTool(this.mouseX,this.mouseY); } } return false; }; this.OnKeyDown=function(e){ if(e.keyCode==27){ this.CancelTool(); } }; this.OnMouseWheel=function(e){ if(this.isDragging||!this.EnableMouseWheel()){ return; } this.OnResize(); this.GetImageXY(e); e=e?e:window.event; var _a3=e.detail?e.detail*-1:e.wheelDelta/40; var res=__cancelEvent(e); this.OnWheel(_a3>0,this.mouseX,this.mouseY); return res; }; this.GetImageXY=function(_a5){ if(_a5.pageX){ this.mouseX=_a5.pageX; this.mouseY=_a5.pageY; }else{ if(document.documentElement&&document.documentElement.scrollTop){ this.mouseX=_a5.clientX+document.documentElement.scrollLeft-2; this.mouseY=_a5.clientY+document.documentElement.scrollTop-2; }else{ this.mouseX=_a5.clientX+document.body.scrollLeft-2; this.mouseY=_a5.clientY+document.body.scrollTop-2; } } this.mouseX=this.mouseX-this.hspc; this.mouseY=this.mouseY-this.vspc; }; this.Init=function(_a6,_a7,_a8){ var _a9=_a6+""_Canvas""; this.MapID=_a6; this.UniqueID=_a7; this.ZoomBarVar=_a8; this.MapCanvas=new jsGraphicsEx(_a9); this.MapCanvas.setStroke(1); this.MapCanvas.setColor(""#FF0000""); this.MapCanvas.setFont(""verdana,geneva,helvetica,sans-serif"",""12px"",""font-weight:bold;""); this.UpdateCursor(); }; this.MapWidth=function(){ return parseInt(this.GetMapCanvas().style.width); }; this.MapHeight=function(){ return parseInt(this.GetMapCanvas().style.height); }; this.OnResize=function(){ try{ this.vspc=0; this.hspc=0; var _aa=this.GetMapCanvas(); do{ this.hspc+=_aa.offsetLeft; this.vspc+=_aa.offsetTop; }while((_aa=_aa.offsetParent)); } catch(ex){ } }; this.GetMapCanvas=function(){ return __$(this.MapID+""_Canvas""); }; this.GetMapImg=function(){ return __$(this.MapID+""_Image""); }; this.Show=function(){ var div=__$(this.MapID); if(div){ div.style.visibility=""visible""; } if(this.GetZoomBar()){ this.GetZoomBar().show(); } this.UpdateBackLayerVisibility(); }; this.Hide=function(){ var div=__$(this.MapID); if(div){ div.style.visibility=""hidden""; } if(this.GetZoomBar()){ this.GetZoomBar().hide(); } this.UpdateBackLayerVisibility(); }; this.UpdateMapVisibility=function(){ if(this.IsVisible()){ this.Show(); }else{ this.Hide(); } }; this.OnPointTool=function(x,y){ var _af=false; if(this.pointToolHandler){ try{ _af=this.pointToolHandler(this.apiVar,this.GetMouseEventArgs(true)); } catch(e){ } } if(!_af){ this.Submit(x,y,""""); } }; this.OnRectTool=function(x1,y1,x2,y2){ this.Submit(this.pack(x1,x2),this.pack(y1,y2),""""); }; this.OnLineTool=function(x1,y1,x2,y2){ this.OnRectTool(x1,y1,x2,y2); }; this.OnCircleTool=function(x,y,_ba){ this.Submit(x,y,_ba); }; this.OnPolylineTool=function(_bb,_bc){ this.Submit(_bb.join("";""),_bc.join("";""),""""); }; this.OnPolygonTool=function(_bd,_be){ this.Submit(_bd.join("";""),_be.join("";""),""""); }; this.OnZoomInTool=function(x,y){ this.Submit(x,y,""""); }; this.OnZoomInRectTool=function(x1,y1,x2,y2){ this.OnRectTool(x1,y1,x2,y2); }; this.OnZoomOutTool=function(x,y){ this.Submit(x,y,""""); }; this.OnCenterTool=function(x,y){ this.Submit(x,y,""""); }; this.OnInfoTool=function(x,y){ var _cb=false; if(this.infoToolHandler){ try{ _cb=this.infoToolHandler(this.apiVar,this.GetMouseEventArgs(true)); } catch(e){ } } if(!_cb){ this.Submit(x,y,""""); } }; this.OnWheel=function(_cc,x,y){ if(_cc){ var cx=Math.round(this.MapWidth()/2+(x-this.MapWidth()/2)/2); var cy=Math.round(this.MapHeight()/2+(y-this.MapHeight()/2)/2); this.AnimateZoom(x,y,_cc); this.SubmitTool(this.TOOL_ZOOMIN,cx,cy,""""); }else{ var xy=this.Rotate(this.MapWidth()/2,this.MapHeight()/2,x-this.MapWidth()/2,y-this.MapHeight()/2,180); this.AnimateZoom(x,y,_cc); this.SubmitTool(this.TOOL_ZOOMOUT,xy.x,xy.y,""""); } }; this.AnimateZoom=function(x,y,_d4){ var _d5=""""; if(_d4){ _d5=""aspmap_whzi""; }else{ _d5=""aspmap_whzo""; } var img=__$(_d5); if(img){ var ext=__getDivExt(this.MapID); img.style.left=(ext.left+x-29)+""px""; img.style.top=(ext.top+y-29)+""px""; img.src=img.src; img.style.display=""block""; setTimeout(""try{__$('""+_d5+""').style.display = 'none';}catch(e){}"",320); } }; this.Rotate=function(_d8,_d9,x,y,_dc){ _dc=(_dc)*Math.PI/180; var px=Math.round(x*Math.cos(_dc)-y*Math.sin(_dc)+_d8); var py=Math.round(x*Math.sin(_dc)+y*Math.cos(_dc)+_d9); return {x:px,y:py}; }; this.OnQuickInfoTool=function(x,y){ this.SetCmdParams(this.GetTool(),this.GetArgument(),x,y,""""); this.qInfoX=x; this.qInfoY=y; map_callback(this.UniqueID,__showQuickInfo,""QINFO"",this); this.SetCmdParams(this.GetTool(),this.GetArgument(),"""","""",""""); }; this.HotspotInfoClick=function(_e1,xy){ var _e3=xy.split("",""); this.qInfoX=parseInt(_e3[0]); this.qInfoY=parseInt(_e3[1]); map_callback(this.UniqueID,__showQuickInfo,""HINFO""+_e1,this); }; this.MarkerClick=function(_e4,_e5,_e6){ var _e7=false; if(this.markerClickHandler){ try{ var _e8=new AspMap.MarkerClickEventArgs(); _e8.argument=_e4; _e8.content=""""; var _e9=__$(this.MapID+""c""+_e5); if(_e9){ _e8.content=_e9.innerHTML; } _e7=this.markerClickHandler(this.apiVar,_e8); } catch(e){ } } if(!_e7&&_e6.length>0){ eval(_e6); } }; this.MarkerInfo=function(_ea,x,y){ this.qInfoX=parseInt(x); this.qInfoY=parseInt(y); var _ed=__$(this.MapID+""c""+_ea); if(_ed){ this.ShowInfo(_ed.innerHTML); } }; this.HideInfoWindow=function(){ __hideQuickInfo(this.MapID); }; this.ShowInfo=function(_ee){ if(_ee.length==0){ return; } var _ef=__$(this.MapID+""_infodiv""); if(!_ef){ return; } var _f0=__$(this.MapID+""_infoct""); if(!_f0){ return; } var _f1=__$(this.MapID+""_infodivc""); if(!_f1){ return; } var _f2=__$(""iwui$""); if(!_f2){ return; } __hideQuickInfo(this.MapID); _f1.innerHTML=_f2.innerHTML.replace(""iwctnt"",_ee); var x=this.qInfoX; var y=this.qInfoY; var _f5=__getDivW(_ef); var _f6=__getDivH(_ef); var _f7=this.MapWidth(); var _f8=this.MapHeight(); var _f9=12; var _fa=20; var _fb=20; var _fc=0; var _fd=0; if(_f5<=_f7){ _fc=x-_f5/2-_fa/2; if(_fc+_f5>_f7){ var d=_fc+_f5-_f7+1; if(_f7-x<=_f9){ d-=_f9-(_f7-x)+1; } _fc-=d; } if(_fc<=0){ var d=Math.abs(_fc); if(x<=_fa+_f9){ d-=_fa+_f9-x; }else{ d+=1; } _fc+=d; } }else{ _fc=x-_f5/2-_fa/2; if(_fc<=0){ var d=Math.abs(_fc); if(x<_fa+_f9){ d-=_fa+_f9-x; }else{ d+=1; } _fc+=d; }else{ _fc=1; } } x-=_fa; if(((y+_f6+_fb>=_f8)||(y-_f6-_fb>0))&&(y-_f6-_fb)>=0){ _fd=y-_f6-_fb; y-=22; }else{ _fd=y+_fb; } if(_fd>y){ _f0.src=__$(""rtct$"").src; }else{ _f0.src=__$(""rbct$"").src; } _ef.style.left=_fc+""px""; _ef.style.top=_fd+""px""; _f0.style.left=x+""px""; _f0.style.top=y+""px""; _f0.style.visibility=""visible""; _ef.style.visibility=""visible""; }; this.Submit=function(x,y,arg){ this.HideInfoWindow(); this.SetCmdParams(this.GetTool(),this.GetArgument(),x,y,arg); __submitMapToolCmd(); }; this.SubmitTool=function(tool,x,y,arg){ this.HideInfoWindow(); this.SetCmdParams(this.GetTool(),this.GetArgument(),x,y,arg); this.SetOverrideTool(tool); __submitMapToolCmd(); }; this.SetCmdParams=function(tool,targ,x,y,arg){ __$(this.MapID+""_arg"").value=arg; __$(this.MapID+""_targ"").value=targ; __$(this.MapID+""_tool"").value=tool; __$(this.MapID+""_x"").value=x; __$(this.MapID+""_y"").value=y; }; this.SetInfoCursor=function(){ this.GetMapCanvas().style.cursor=""help""; }; this.SetCrossCursor=function(){ this.GetMapCanvas().style.cursor=""crosshair""; }; this.SetPanCursor=function(){ this.GetMapCanvas().style.cursor=""move""; }; this.SetPanCursorForInfo=function(){ var c=this.GetStr(""_curspan""); if(c.length>0){ this.GetMapCanvas().style.cursor=c; } }; this.SetDefCursor=function(){ this.GetMapCanvas().style.cursor=""default""; }; this.GetCursor=function(){ return __$(this.MapID+""_curs"").value; }; this.SetCursor=function(c){ if(c==null){ return; } __$(this.MapID+""_curs"").value=c; if(c.length>0){ this.GetMapCanvas().style.cursor=c; return; } var tool=this.GetTool(); if(tool==this.TOOL_CENTER){ this.SetCrossCursor(); }else{ if(tool==this.TOOL_PAN){ this.SetPanCursor(); }else{ if(tool==this.TOOL_INFO||tool==this.TOOL_QINFO){ this.SetInfoCursor(); }else{ this.SetDefCursor(); } } } }; this.HideToolTips=function(){ __TT.hideToolpipsFromTracking(); }; this.GetMapTool=function(){ return parseInt(__$(this.MapID+""_tool"").value); }; this.SetMapTool=function(tool){ __$(this.MapID+""_tool"").value=tool; }; this.SetOverrideTool=function(tool){ __$(this.MapID+""_otool"").value=tool; }; this.SetApiCall=function(){ __$(this.MapID+""_api"").value=""1""; }; this.SetToolArgument=function(arg){ __$(this.MapID+""_targ"").value=arg; }; this.GetToolArgument=function(){ return __$(this.MapID+""_targ"").value; }; this.mpp=function(){ return parseFloat(__$(this.MapID+""_mpp"").value); }; this.miles=function(){ return __$(this.MapID+""_mis"").value; }; this.feet=function(){ return __$(this.MapID+""_fts"").value; }; this.km=function(){ return __$(this.MapID+""_kms"").value; }; this.meters=function(){ return __$(this.MapID+""_mts"").value; }; this.LineWidth=function(){ return parseInt(__$(this.MapID+""_tlw"").value); }; this.LineColor=function(){ return __$(this.MapID+""_tlc"").value; }; this.EnablePan=function(){ return __$(this.MapID+""_enpan"").value==""1""; }; this.EnableMouseWheel=function(){ return __$(this.MapID+""_emw"").value==""1""; }; this.BackLayerService=function(){ var s=__$(this.MapID+""blservice""); if(s){ return s.value; } return null; }; this.BackLayerType=function(){ var s=__$(this.MapID+""bltype""); if(s){ return parseInt(s.value); } return 0; }; this.BackLayerVisible=function(){ var s=__$(this.MapID+""blvisible""); if(s){ return s.value==""1""; } return false; }; this.IsVisible=function(){ return this.GetBool(""_vis""); }; this.SetVisible=function(_114){ this.SetBool(""_vis"",_114); this.UpdateMapVisibility(); }; this.GetDbl=function(_115){ return parseFloat(this.GetStr(_115)); }; this.SetDbl=function(_116,_117){ this.SetStr(_116,_117); }; this.GetBool=function(_118){ return this.GetStr(_118)==""1""; }; this.SetBool=function(_119,_11a){ this.SetStr(_119,_11a?""1"":""0""); }; this.GetInt=function(_11b){ return parseInt(this.GetStr(_11b)); }; this.SetInt=function(_11c,_11d){ this.SetStr(_11c,Math.round(_11d)); }; this.GetStr=function(_11e){ return __$(this.MapID+_11e).value; }; this.SetStr=function(_11f,_120){ __$(this.MapID+_11f).value=_120; }; this.pack=function(a,b){ return (a+"";""+b); }; this.Print=function(){ var _123=null; try{ var html=__$(this.MapID).innerHTML; var _125=/[o]n[a-zA-Z0-9]+=""[^""]*""/g; html=html.replace(_125,""""); var _126=frames[""amprnfr""]; _123=_126.document.getElementById(""content""); _123.style.position=""relative""; _123.style.width=this.MapWidth()+""px""; _123.style.height=this.MapHeight()+""px""; _123.innerHTML=html; var _127=_126.document.getElementById(this.MapID+""_Canvas""); _127.style.backgroundImage=""""; var _128=__$(this.MapID+""bglayer"").cloneNode(true); _128.style.left=""0px""; _128.style.top=""0px""; _128.style.zIndex=0; _123.appendChild(_128); _126.document.body.style.visibility=""visible""; _126.focus(); _126.prn(); } catch(e){ } }; this.backLayerDiv=null; this.backLayer=null; this.InitBackLayerDiv=function(){ var _129=document.createElement(""div""); _129.style.position=""absolute""; _129.id=this.MapID+""bglayer""; this.InitBackLayerSize(_129); _129.style.zIndex=""180""; _129.style.visibility=""hidden""; document.body.appendChild(_129); this.backLayerDiv=_129; var _12a=this.BackLayerService(); if(_12a){ if(_12a==""google""){ this.backLayer=new AspMapGM(this.backLayerDiv,this.BackLayerType()); }else{ if(_12a==""ve""){ this.backLayer=new AspMapVE(this.backLayerDiv,this.BackLayerType()); } } if(this.backLayer.IsValid()){ this.backLayer.CenterAndZoom(this.GetCenterLatLong(),this.GetZoom()); if(this.BackLayerVisible()&&this.IsVisible()){ _129.style.visibility=""visible""; } }else{ this.backLayer=null; } } }; this.UpdateBackLayer=function(){ if(this.backLayer){ this.UpdateBackLayerVisibility(); this.backLayer.SetMapType(this.BackLayerType()); this.backLayer.CenterAndZoom(this.GetCenterLatLong(),this.GetZoom()); } }; this.UpdateBackLayerVisibility=function(){ if(this.backLayer){ if(this.BackLayerVisible()&&this.IsVisible()){ this.backLayerDiv.style.visibility=""visible""; }else{ this.backLayerDiv.style.visibility=""hidden""; } } }; this.PanBackLayer=function(dx,dy){ if(this.backLayer){ this.backLayer.Pan(dx,dy); } }; this.ResizeBackLayer=function(){ if(this.backLayerDiv){ this.InitBackLayerSize(this.backLayerDiv); if(this.backLayer){ this.backLayer.Resize(this.MapWidth(),this.MapHeight()); } } }; this.InitBackLayerSize=function(div){ var ext=__getDivExt(this.MapID); if(ext==null){ return; } div.style.left=ext.left+""px""; div.style.top=ext.top+""px""; div.style.width=this.MapWidth()+""px""; div.style.height=this.MapHeight()+""px""; }; this.load=function(){ this.RegisterAspAjaxHandlers(); this.InitBackLayerDiv(); this.UpdateMapVisibility(); }; this.pageLoaded=function(_12f,args){ this.UpdateMapVisibility(); this.ResizeBackLayer(); this.UpdateBackLayer(); }; this.resize=function(e){ this.ResizeBackLayer(); }; __addHandlerCtx(window,""load"",this); __addHandlerCtx(window,""resize"",this); this.RegisterAspAjaxHandlers=function(){ try{ Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(__getAjaxEventCtx(this,""pageLoaded"")); } catch(ex){ } }; } __addHandler(window,""load"",__amAspAjaxInit); var __amIsAspAjaxCall=false; var __amEventValidation=null; function __amAspAjaxInit(){ try{ Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(__amAspAjaxBeginRequest); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(__amAspAjaxEndRequest); } catch(ex){ } } function __amAspAjaxBeginRequest(_132,args){ __amIsAspAjaxCall=true; try{ __TT.H(); } catch(e){ } } function __amAspAjaxEndRequest(_134,args){ __amIsAspAjaxCall=false; try{ var ev=__$(""__EVENTVALIDATION""); if(ev){ __amEventValidation=ev.value; } } catch(ex){ } } function __amUpdateEventValidation(){ try{ if(__amEventValidation){ var ev=__$(""__EVENTVALIDATION""); if(ev){ ev.value=__amEventValidation; } } } catch(ex){ } } function AspMapGM(div,_139){ this.mapObj=null; this.dragObj=null; this.IsValid=function(){ return (this.mapObj!=null); }; this.CenterAndZoom=function(_13a,zoom){ if(!this.IsValid()){ return; } try{ this.mapObj.setCenter(new GLatLng(_13a.y,_13a.x),zoom); } catch(e){ } }; this.Pan=function(dx,dy){ if(!this.IsValid()){ return; } try{ this.dragObj.moveBy(new GSize(dx,dy)); } catch(e){ } }; this.SetMapType=function(type){ if(!this.IsValid()){ return; } try{ switch(type){ case 0: this.mapObj.setMapType(G_NORMAL_MAP); break; case 1: this.mapObj.setMapType(G_SATELLITE_MAP); break; case 2: this.mapObj.setMapType(G_HYBRID_MAP); break; case 3: this.mapObj.setMapType(G_PHYSICAL_MAP); break; } } catch(e){ } }; this.Resize=function(_13f,_140){ if(!this.IsValid()){ return; } try{ this.mapObj.checkResize(); } catch(e){ } }; try{ this.mapObj=new GMap2(div); this.SetMapType(_139); if(typeof this.mapObj.getDragObject==""function""){ this.dragObj=this.mapObj.getDragObject(); } } catch(e){ this.mapObj=null; } } function AspMapVE(div,_142){ this.mapObj=null; this.dragObj=null; this.IsValid=function(){ return (this.mapObj!=null); }; this.CenterAndZoom=function(_143,zoom){ if(!this.IsValid()){ return; } try{ this.mapObj.SetCenterAndZoom(new VELatLong(_143.y,_143.x),zoom+1); } catch(e){ } }; this.Pan=function(dx,dy){ if(!this.IsValid()){ return; } try{ this.mapObj.vemapcontrol.PanMap(-dx,-dy); } catch(e){ } }; this.SetMapType=function(type){ if(!this.IsValid()){ return; } try{ switch(type){ case 0: this.mapObj.SetMapStyle(VEMapStyle.Road); break; case 1: this.mapObj.SetMapStyle(VEMapStyle.Aerial); break; case 2: this.mapObj.SetMapStyle(VEMapStyle.Hybrid); break; } } catch(e){ } }; this.Resize=function(_148,_149){ if(!this.IsValid()){ return; } try{ this.mapObj.Resize(_148,_149); } catch(e){ } }; try{ this.mapObj=new VEMap(div.id); if(this.mapObj!=null){ try{ this.mapObj.LoadMap(null,null,null,true); this.mapObj.AttachEvent(""onmousedown"",function(){ return true; }); } catch(e){ } this.SetMapType(_142); this.mapObj.HideDashboard(); } } catch(e){ this.mapObj=null; } } function AspMapZoomBar(_14a,_14b,_14c,_14d,_14e,pos){ this.mapID=_14b; this.clientID=_14a; this.showBar=_14e; this.levelCount=_14c; this.levelH=_14d; this.drag=false; this.pos=pos; this.mousedown=function(e){ if(!this.showBar){ return true; } if(e.preventDefault){ e.preventDefault(); } this.drag=true; return false; }; this.mousemove=function(e){ if(!this.drag||!this.showBar){ return true; } this.moveThumb(e); return false; }; this.mouseup=function(e){ if(!this.drag||!this.showBar){ return true; } this.drag=false; var _153=this.moveThumb(e); if(_153>=0){ var map=__getMapTools(this.mapID); if(!map){ return false; } map.SetZoom(_153); } return false; }; this.resize=function(e){ if(this.drag){ return true; } if(this.pos==0){ return true; } var ext=__getDivExt(this.mapID); if(!ext){ return true; } var div=__$(this.clientID); div.style.top=ext.top+4+""px""; if(this.pos==1){ div.style.left=ext.left+4+""px""; }else{ div.style.left=ext.right-__getDivW(div)-4+""px""; } var map=__getMapTools(this.mapID); if(map&&map.IsVisible()){ this.show(); } return true; }; this.show=function(){ var div=__$(this.clientID); if(div){ div.style.visibility=""visible""; } }; this.hide=function(){ var div=__$(this.clientID); if(div){ div.style.visibility=""hidden""; } }; this.load=function(e){ this.resize(); return true; }; this.moveThumb=function(e){ e=e||window.event; var _15d=this.getMouseY(this.barID(),e); var barH=__getDivH(__$(this.barID())); var _15f=0; if(_15d<=0){ _15f=this.levelCount-1; }else{ if(_15d>=barH){ _15f=0; }else{ _15f=this.mouseToLevel(_15d); } } if(_15f<0||_15f>=this.levelCount){ return -1; } this.updateThumb(_15f); return _15f; }; this.updateThumb=function(_160){ if(_160<0||_160>=this.levelCount){ return; } var _161=__$(this.thumbID()); if(!_161){ return; } var _162=__getDivH(_161); _161.style.top=(this.levelCount-_160-1)*this.levelH-Math.round((_162-this.levelH)/2)+""px""; }; this.mouseToLevel=function(_163){ return this.levelCount-Math.floor(_163/this.levelH)-1; }; this.getMouseY=function(_164,ev){ var _166=__$(_164); if(!_166){ return 0; } var top=0,y=0; while(_166.offsetParent){ top+=_166.offsetTop; _166=_166.offsetParent; } top+=_166.offsetTop; var _169=__$(this.clientID); top+=Math.round((_169.offsetHeight-_169.clientHeight)/2); ev=ev||window.event; if(ev.pageY){ y=ev.pageY; }else{ if(document.documentElement&&document.documentElement.scrollTop){ y=ev.clientY+document.documentElement.scrollTop-document.documentElement.clientTop; }else{ y=ev.clientY+document.body.scrollTop-document.body.clientTop; } } return y-top; }; this.thumbID=function(){ return this.clientID+""_th""; }; this.barID=function(){ return this.clientID+""_bar""; }; this.pageLoaded=function(_16a,args){ var _16c=__getMapTools(this.mapID); if(_16c==null){ return; } this.resize(); this.updateThumb(_16c.GetZoom()); }; if(this.showBar){ __addHandlerCtx(document.body,""mousemove"",this); __addHandlerCtx(document.body,""mouseup"",this); __addHandlerCtx(__$(this.thumbID()),""mousedown"",this); } if(this.pos>0){ __addHandlerCtx(window,""load"",this); __addHandlerCtx(window,""resize"",this); this.resize(null); } try{ Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(__getAjaxEventCtx(this,""pageLoaded"")); } catch(ex){ } } function __selectMapTool(_16d,_16e,_16f,arg){ if(_16f==null){ return; } var _171=__$(_16d+""_tbutt""); if(_171==null){ return; } var _172=__$(_171.value); var _173=__getMapTools(_16d); if(_173==null){ return; } _173.SetTool(_16e); _173.SetArgument(arg); var attr=_16f.getAttribute(""curs""); if(attr!=null){ _173.SetCursor(attr); } if(_172){ var attr=_172.getAttribute(""normimg""); if(attr!=null){ _172.src=attr; } attr=_172.getAttribute(""normbord""); if(attr!=""notset""){ _172.style.borderStyle=attr; } } attr=_16f.getAttribute(""selimg""); if(attr!=null){ _16f.src=attr; } attr=_16f.getAttribute(""selbord""); if(attr!=""notset""){ _16f.style.borderStyle=attr; } _171.value=_16f.id; } function __markerClick(_175,_176,_177,_178){ var map=__getMapTools(_175); if(map){ map.MarkerClick(_176,_177,_178); } } function __markerInfo(_17a,_17b,x,y){ var map=__getMapTools(_17a); if(map){ map.MarkerInfo(_17b,x,y); } } function __hsInfo(_17f,_180,xy){ var map=__getMapTools(_17f); if(map){ map.HotspotInfoClick(_180,xy); } } function __showQuickInfo(_183,_184){ if(!_183||_183.length==0||!_184){ return; } _184.ShowInfo(_183); } function __hideQuickInfo(_185){ try{ __$(_185+""_infodiv"").style.visibility=""hidden""; __$(_185+""_infoct"").style.visibility=""hidden""; } catch(e){ } } function __$(id){ if(id==null||id.length==0){ return null; } var elem=(document.getElementById?document.getElementById(id):document.all?document.all[id]:null); if(elem==null){ var _188=document.getElementsByName(id); if(_188!=null){ elem=_188[0]; } } return elem; } function __getDivExt(_189){ var _18a=__$(_189); if(!_18a){ return null; } var top=0,left=0; var div=_18a; while(_18a.offsetParent){ top+=_18a.offsetTop; left+=_18a.offsetLeft; _18a=_18a.offsetParent; } top+=_18a.offsetTop; left+=_18a.offsetLeft; return {left:left,top:top,right:left+__getDivW(div),bottom:top+__getDivH(div)}; } function __getDivW(el){ return (el?(el.offsetWidth||el.style.pixelWidth||0):0); } function __getDivH(el){ return (el?(el.offsetHeight||el.style.pixelHeight||0):0); } function __clearDiv(elem){ if(elem){ while(elem.hasChildNodes()){ elem.removeChild(elem.firstChild); } elem.innerHTML=""""; } } function __cancelEvent(e){ e=e?e:window.event; if(e.stopPropagation){ e.stopPropagation(); } if(e.preventDefault){ e.preventDefault(); } e.cancelBubble=true; e.cancel=true; e.returnValue=false; return false; } function __MWFF(_192,_193){ var el=__$(_192); if(!el){ return; } if(el.addEventListener){ el.addEventListener(""DOMMouseScroll"",_193,false); } } function __addHandler(el,_196,_197){ if(!el){ return; } if(el.addEventListener){ el.addEventListener(_196,_197,false); }else{ if(el.attachEvent){ el.attachEvent(""on""+_196,_197); }else{ el[""on""+_196]=_197; } } } function __addHandlerCtx(el,_199,_19a){ var _19b=__getHandlerCtx(_19a,_199); __addHandler(el,_199,_19b); } function __getHandlerCtx(_19c,_19d){ return (function(e){ return _19c[_19d](e); }); } function __getAjaxEventCtx(_19f,_1a0){ return (function(_1a1,args){ return _19f[_1a0](_1a1,args); }); } function __getMapTools(_1a3){ var _1a4=null; try{ _1a4=eval(_1a3.toLowerCase()+""_tools""); } catch(ex){ } return _1a4; } function __getMapToolsName(_1a5){ return _1a5.toLowerCase()+""_tools""; } var jg_ok,jg_ie,jg_fast,jg_dom,jg_moz; function chkDHTM(x,i){ x=document.body||null; jg_ie=x&&typeof x.insertAdjacentHTML!=""undefined""&&document.createElement; jg_dom=(x&&!jg_ie&&typeof x.appendChild!=""undefined""&&typeof document.createRange!=""undefined""&&typeof (i=document.createRange()).setStartBefore!=""undefined""&&typeof i.createContextualFragment!=""undefined""); jg_fast=jg_ie&&document.all&&!window.opera; jg_moz=jg_dom&&typeof x.style.MozOpacity!=""undefined""; jg_ok=!!(jg_ie||jg_dom); } function pntCnvDom(){ var x=this.wnd.document.createRange(); var _1a9=this.cnv(); x.setStartBefore(_1a9); x=x.createContextualFragment(jg_fast?this.htmRpc():this.htm); if(_1a9){ _1a9.appendChild(x); } this.htm=""""; } function pntCnvIe(){ var _1aa=this.cnv(); if(_1aa){ _1aa.insertAdjacentHTML(""BeforeEnd"",jg_fast?this.htmRpc():this.htm); } this.htm=""""; } function pntDoc(){ this.wnd.document.write(jg_fast?this.htmRpc():this.htm); this.htm=""""; } function pntN(){ } function mkDiv(x,y,w,h){ this.htm+=""
    ""; } function mkDivIe(x,y,w,h){ this.htm+=""%%""+this.color+"";""+x+"";""+y+"";""+w+"";""+h+"";""; } function mkDivPrt(x,y,w,h){ this.htm+=""
    ""; } var regex=/%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g; function htmRpc(){ return this.htm.replace(regex,""
    \\n""); } function htmPrtRpc(){ return this.htm.replace(regex,""
    \\n""); } function mkLin(x1,y1,x2,y2){ if(x1>x2){ var _x2=x2; var _y2=y2; x2=x1; y2=y1; x1=_x2; y1=_y2; } var dx=x2-x1,dy=Math.abs(y2-y1),x=x1,y=y1,_1c1=(y1>y2)?-1:1; if(dx>=dy){ var pr=dy<<1,pru=pr-(dx<<1),p=pr-dx,ox=x; while(dx>0){ --dx; ++x; if(p>0){ this.mkDiv(ox,y,x-ox,1); y+=_1c1; p+=pru; ox=x; }else{ p+=pr; } } this.mkDiv(ox,y,x2-ox+1,1); }else{ var pr=dx<<1,pru=pr-(dy<<1),p=pr-dy,oy=y; if(y2<=y1){ while(dy>0){ --dy; if(p>0){ this.mkDiv(x++,y,1,oy-y+1); y+=_1c1; p+=pru; oy=y; }else{ y+=_1c1; p+=pr; } } this.mkDiv(x2,y2,1,oy-y2+1); }else{ while(dy>0){ --dy; y+=_1c1; if(p>0){ this.mkDiv(x++,oy,1,y-oy); p+=pru; oy=y; }else{ p+=pr; } } this.mkDiv(x2,oy,1,y2-oy+1); } } } function mkLin2D(x1,y1,x2,y2){ if(x1>x2){ var _x2=x2; var _y2=y2; x2=x1; y2=y1; x1=_x2; y1=_y2; } var dx=x2-x1,dy=Math.abs(y2-y1),x=x1,y=y1,_1d1=(y1>y2)?-1:1; var s=this.stroke; if(dx>=dy){ if(dx>0&&s-3>0){ var _s=(s*dx*Math.sqrt(1+dy*dy/(dx*dx))-dx-(s>>1)*dy)/dx; _s=(!(s-4)?Math.ceil(_s):Math.round(_s))+1; }else{ var _s=s; } var ad=Math.ceil(s/2); var pr=dy<<1,pru=pr-(dx<<1),p=pr-dx,ox=x; while(dx>0){ --dx; ++x; if(p>0){ this.mkDiv(ox,y,x-ox+ad,_s); y+=_1d1; p+=pru; ox=x; }else{ p+=pr; } } this.mkDiv(ox,y,x2-ox+ad+1,_s); }else{ if(s-3>0){ var _s=(s*dy*Math.sqrt(1+dx*dx/(dy*dy))-(s>>1)*dx-dy)/dy; _s=(!(s-4)?Math.ceil(_s):Math.round(_s))+1; }else{ var _s=s; } var ad=Math.round(s/2); var pr=dx<<1,pru=pr-(dy<<1),p=pr-dy,oy=y; if(y2<=y1){ ++ad; while(dy>0){ --dy; if(p>0){ this.mkDiv(x++,y,_s,oy-y+ad); y+=_1d1; p+=pru; oy=y; }else{ y+=_1d1; p+=pr; } } this.mkDiv(x2,y2,_s,oy-y2+ad); }else{ while(dy>0){ --dy; y+=_1d1; if(p>0){ this.mkDiv(x++,oy,_s,y-oy+ad); p+=pru; oy=y; }else{ p+=pr; } } this.mkDiv(x2,oy,_s,y2-oy+ad+1); } } } function mkOv(left,top,_1dc,_1dd){ var a=(++_1dc)>>1,b=(++_1dd)>>1,wod=_1dc&1,hod=_1dd&1,cx=left+a,cy=top+b,x=0,y=b,ox=0,oy=b,aa2=(a*a)<<1,aa4=aa2<<1,bb2=(b*b)<<1,bb4=bb2<<1,st=(aa2>>1)*(1-(b<<1))+bb2,tt=(bb2>>1)-aa2*((b<<1)-1),w,h; while(y>0){ if(st<0){ st+=bb2*((x<<1)+3); tt+=bb4*(++x); }else{ if(tt<0){ st+=bb2*((x<<1)+3)-aa4*(y-1); tt+=bb4*(++x)-aa2*(((y--)<<1)-3); w=x-ox; h=oy-y; if((w&2)&&(h&2)){ this.mkOvQds(cx,cy,x-2,y+2,1,1,wod,hod); this.mkOvQds(cx,cy,x-1,y+1,1,1,wod,hod); }else{ this.mkOvQds(cx,cy,x-1,oy,w,h,wod,hod); } ox=x; oy=y; }else{ tt-=aa2*((y<<1)-3); st-=aa4*(--y); } } } w=a-ox+1; h=(oy<<1)+hod; y=cy-oy; this.mkDiv(cx-a,y,w,h); this.mkDiv(cx+ox+wod-1,y,w,h); } function mkOv2D(left,top,_1f2,_1f3){ var s=this.stroke; _1f2+=s+1; _1f3+=s+1; var a=_1f2>>1,b=_1f3>>1,wod=_1f2&1,hod=_1f3&1,cx=left+a,cy=top+b,x=0,y=b,aa2=(a*a)<<1,aa4=aa2<<1,bb2=(b*b)<<1,bb4=bb2<<1,st=(aa2>>1)*(1-(b<<1))+bb2,tt=(bb2>>1)-aa2*((b<<1)-1); if(s-4<0&&(!(s-2)||_1f2-51>0&&_1f3-51>0)){ var ox=0,oy=b,w,h,pxw; while(y>0){ if(st<0){ st+=bb2*((x<<1)+3); tt+=bb4*(++x); }else{ if(tt<0){ st+=bb2*((x<<1)+3)-aa4*(y-1); tt+=bb4*(++x)-aa2*(((y--)<<1)-3); w=x-ox; h=oy-y; if(w-1){ pxw=w+1+(s&1); h=s; }else{ if(h-1){ pxw=s; h+=1+(s&1); }else{ pxw=h=s; } } this.mkOvQds(cx,cy,x-1,oy,pxw,h,wod,hod); ox=x; oy=y; }else{ tt-=aa2*((y<<1)-3); st-=aa4*(--y); } } } this.mkDiv(cx-a,cy-oy,s,(oy<<1)+hod); this.mkDiv(cx+a+wod-s,cy-oy,s,(oy<<1)+hod); }else{ var _a=(_1f2-(s<<1))>>1,_b=(_1f3-(s<<1))>>1,_x=0,_y=_b,_aa2=(_a*_a)<<1,_aa4=_aa2<<1,_bb2=(_b*_b)<<1,_bb4=_bb2<<1,_st=(_aa2>>1)*(1-(_b<<1))+_bb2,_tt=(_bb2>>1)-_aa2*((_b<<1)-1),pxl=new Array(),pxt=new Array(),_pxb=new Array(); pxl[0]=0; pxt[0]=b; _pxb[0]=_b-1; while(y>0){ if(st<0){ pxl[pxl.length]=x; pxt[pxt.length]=y; st+=bb2*((x<<1)+3); tt+=bb4*(++x); }else{ if(tt<0){ pxl[pxl.length]=x; st+=bb2*((x<<1)+3)-aa4*(y-1); tt+=bb4*(++x)-aa2*(((y--)<<1)-3); pxt[pxt.length]=y; }else{ tt-=aa2*((y<<1)-3); st-=aa4*(--y); } } if(_y>0){ if(_st<0){ _st+=_bb2*((_x<<1)+3); _tt+=_bb4*(++_x); _pxb[_pxb.length]=_y-1; }else{ if(_tt<0){ _st+=_bb2*((_x<<1)+3)-_aa4*(_y-1); _tt+=_bb4*(++_x)-_aa2*(((_y--)<<1)-3); _pxb[_pxb.length]=_y-1; }else{ _tt-=_aa2*((_y<<1)-3); _st-=_aa4*(--_y); _pxb[_pxb.length-1]--; } } } } var ox=-wod,oy=b,_oy=_pxb[0],l=pxl.length,w,h; for(var i=0;i0){ this.drawLine=mkLin2D; this.mkOv=mkOv2D; this.drawRect=mkRect; }else{ this.drawLine=mkLin; this.mkOv=mkOv; this.drawRect=mkRect; } } }; this.setPrintable=function(arg){ this.printable=arg; if(jg_fast){ this.mkDiv=mkDivIe; this.htmRpc=arg?htmPrtRpc:htmRpc; }else{ this.mkDiv=arg?mkDivPrt:mkDiv; } }; this.setFont=function(fam,sz,sty){ this.ftFam=fam; this.ftSz=sz; this.ftSty=sty||Font.PLAIN; }; this.drawPolyline=this.drawPolyLine=function(x,y){ for(var i=x.length-1;i;){ --i; this.drawLine(x[i],y[i],x[i+1],y[i+1]); } }; this.fillRect=function(x,y,w,h){ this.mkDiv(x,y,w,h); }; this.drawPolygon=function(x,y){ this.drawPolyline(x,y); this.drawLine(x[x.length-1],y[x.length-1],x[0],y[0]); }; this.drawEllipse=this.drawOval=function(x,y,w,h){ this.mkOv(x,y,w,h); }; this.drawString=function(txt,x,y,_234,_235){ this.htm+=""
    ""+txt+""
    ""; }; this.clear=function(){ this.htm=""""; __clearDiv(this.cnv()); }; this.mkOvQds=function(cx,cy,x,y,w,h,wod,hod){ var xl=cx-x,xr=cx+x+wod-w,yt=cy-y,yb=cy+y+hod-h; if(xr>xl+w){ this.mkDiv(xr,yt,w,h); this.mkDiv(xr,yb,w,h); }else{ w=xr-xl+w; } this.mkDiv(xl,yt,w,h); this.mkDiv(xl,yb,w,h); }; this.setStroke(1); this.setFont(""verdana,geneva,helvetica,sans-serif"",""12px"",Font.PLAIN); this.color=""#000000""; this.htm=""""; this.wnd=wnd||window; this.cnvID=cnv; if(!jg_ok){ chkDHTM(); } if(jg_ok){ if(cnv){ if(typeof (cnv)==""string""){ this.cont=document.all?(this.wnd.document.all[cnv]||null):document.getElementById?(this.wnd.document.getElementById(cnv)||null):null; }else{ if(cnv==window.document){ this.cont=document.getElementsByTagName(""body"")[0]; }else{ this.cont=cnv; } } this.paint=jg_dom?pntCnvDom:pntCnvIe; }else{ this.paint=pntDoc; } }else{ this.paint=pntN; } this.setPrintable(false); this.cnv=function(){ var _242=__$(this.cnvID); var _243=_242.getElementsByTagName(""DIV""); if(_243==null){ return _242; } return _243[0]; }; } function CompInt(x,y){ return (x-y); } function map_enableAutoRefresh(){ alert(""The map_enableAutoRefresh() function has been deprecated. Use the Map.set_enableAnimation property.""); } function map_setAnimationInterval(){ alert(""The map_setAnimationInterval() function has been deprecated. Use the Map.set_animationInterval property.""); } function map_refreshAnimationLayer(){ alert(""The map_refreshAnimationLayer() function has been deprecated. Use the Map.refreshAnimationLayer method.""); } ",16254,False,2433.799800082316,median " <% txtInternalRecordIdentifier = Request.Form(""txtInternalRecordIdentifier"") ProspectName = GetProspectNameByNumber(txtInternalRecordIdentifier) txtPrimaryCompetitor = Request.Form(""txtPrimaryCompetitor"") txtTelemarketerUserNo = Request.Form(""txtTelemarketerUserNo"") txtLeadSourceNumber = Request.Form(""txtLeadSource"") chkBottledWater = Request.Form(""chkBottledWater"") chkFilteredWater = Request.Form(""chkFilteredWater"") chkOCS = Request.Form(""chkOCS"") chkOCS_Supply = Request.Form(""chkOCS_Supply"") chkOfficeSupplies = Request.Form(""chkOfficeSupplies"") chkVending = Request.Form(""chkVending"") chkMicroMarket = Request.Form(""chkMicroMarket"") chkPantry = Request.Form(""chkPantry"") txtFormerCustomerNumber = Request.Form(""txtFormerCustomerNumber"") txtFormerCustomerCancelDate = Request.Form(""txtFormerCustomerCancelDate"") '******************************************************************************************************************* 'GET ORIGINAL VALUES FOR OPPORTUNITY FIELDS FOR AUDIT TRAIL CHANGES '******************************************************************************************************************* SQLProspect = ""SELECT * FROM PR_Prospects WHERE InternalRecordIdentifier = "" & txtInternalRecordIdentifier Set cnnProspect = Server.CreateObject(""ADODB.Connection"") cnnProspect.open (Session(""ClientCnnString"")) Set rsProspect = Server.CreateObject(""ADODB.Recordset"") rsProspect.CursorLocation = 3 Set rsProspect = cnnProspect.Execute(SQLProspect) If not rsProspect.EOF Then ORIG_TelemarketerUserNo = rsProspect(""TelemarketerUserNo"") ORIG_LeadSourceNumber = rsProspect(""LeadSourceNumber"") ORIG_FormerCustNum = rsProspect(""FormerCustNum"") ORIG_FormerCustomerCancelDate = rsProspect(""CancelDate"") End If set rsProspect = Nothing cnnProspect.close set cnnProspect = Nothing If txtPrimaryCompetitor <> """" Then SQLCompetitors = ""SELECT * FROM PR_ProspectCompetitors WHERE ProspectRecID = "" & txtInternalRecordIdentifier & "" AND CompetitorRecID = "" & txtPrimaryCompetitor Response.Write(SQLCompetitors & ""
    "") Set cnnCompetitors = Server.CreateObject(""ADODB.Connection"") cnnCompetitors.open (Session(""ClientCnnString"")) Set rsCompetitors = Server.CreateObject(""ADODB.Recordset"") rsCompetitors.CursorLocation = 3 Set rsCompetitors = cnnCompetitors.Execute(SQLCompetitors) If not rsCompetitors.EOF Then ORIG_CompetitorRecID = rsCompetitors(""CompetitorRecID"") ORIG_PrimaryCompetitor = rsCompetitors(""PrimaryCompetitor"") Orig_BottledWater = rsCompetitors(""BottledWater"") Orig_FilteredWater = rsCompetitors(""FilteredWater"") Orig_OCS = rsCompetitors(""OCS"") Orig_OCS_Supply = rsCompetitors(""OCS_Supply"") Orig_OfficeSupplies = rsCompetitors(""OfficeSupplies"") Orig_Vending = rsCompetitors(""Vending"") Orig_Micromarket = rsCompetitors(""Micromarket"") Orig_Pantry = rsCompetitors(""Pantry"") End If If (Orig_OCS <> """" AND Orig_OCS <> 0) Then Orig_OCS = 1 Else Orig_OCS = 0 If (Orig_OCS_Supply <> """" AND Orig_OCS_Supply <> 0) Then Orig_OCS_Supply = 1 Else Orig_OCS_Supply = 0 If (Orig_BottledWater <> """" AND Orig_BottledWater <> 0) Then Orig_BottledWater = 1 Else Orig_BottledWater = 0 If (Orig_FilteredWater <> """" AND Orig_FilteredWater <> 0) Then Orig_FilteredWater = 1 Else Orig_FilteredWater = 0 If (Orig_Vending <> """" AND Orig_Vending <> 0) Then Orig_Vending = 1 Else Orig_Vending = 0 If (Orig_Micromarket <> """" AND Orig_Micromarket <> 0) Then Orig_Micromarket = 1 Else Orig_Micromarket = 0 If (Orig_Pantry <> """" AND Orig_Pantry <> 0) Then Orig_Pantry = 1 Else Orig_Pantry = 0 If (Orig_OfficeSupplies <> """" AND Orig_OfficeSupplies <> 0) Then Orig_OfficeSupplies = 1 Else Orig_OfficeSupplies = 0 End If '******************************************************************************************************************* 'SET DEFAULT VALUES FOR ANY NON REQUIRED FIELDS LEFT BLANK DURING THE EDIT PROCESS '******************************************************************************************************************* If txtTelemarketerUserNo = """" Then txtTelemarketerUserNo = 0 If ORIG_TelemarketerUserNo= """" Then txtORIG_TelemarketerUserNoLeadSource = 0 If ORIG_CompetitorRecID = """" Then ORIG_CompetitorRecID = 0 If txtPrimaryCompetitor = """" Then txtPrimaryCompetitor = 0 If txtLeadSourceNumber = """" Then txtLeadSourceNumber = 0 If ORIG_LeadSourceNumber = """" Then ORIG_LeadSourceNumber = 0 If (chkBottledWater <> """" AND chkBottledWater = ""on"") Then chkBottledWater = 1 Else chkBottledWater = 0 If (chkFilteredWater <> """" AND chkFilteredWater = ""on"") Then chkFilteredWater = 1 Else chkFilteredWater = 0 If (chkOCS <> """" AND chkOCS = ""on"") Then chkOCS = 1 Else chkOCS = 0 If (chkOCS_Supply <> """" AND chkOCS_Supply = ""on"") Then chkOCS_Supply = 1 Else chkOCS_Supply = 0 If (chkOfficeSupplies <> """" AND chkOfficeSupplies = ""on"") Then chkOfficeSupplies = 1 Else chkOfficeSupplies = 0 If (chkVending <> """" AND chkVending = ""on"") Then chkVending = 1 Else chkVending = 0 If (chkMicroMarket <> """" AND chkMicroMarket = ""on"") Then chkMicroMarket = 1 Else chkMicroMarket = 0 If (chkPantry <> """" AND chkPantry = ""on"") Then chkPantry = 1 Else chkPantry = 0 '******************************************************************************************************************* '******************************************************************************************************************* 'PERFORM SQL UPDATE INTO PR_Prospects AND PR_ProspectCompetitors '******************************************************************************************************************* '****************************************************** 'Update PR_Prospects '****************************************************** SQLProspectUpdate = ""UPDATE PR_Prospects SET LeadSourceNumber = "" & cInt(txtLeadSourceNumber) & "", TelemarketerUserNo = "" & cInt(txtTelemarketerUserNo) & "", "" SQLProspectUpdate = SQLProspectUpdate & ""FormerCustNum = '"" & txtFormerCustomerNumber & ""', CancelDate = '"" & txtFormerCustomerCancelDate & ""' "" SQLProspectUpdate = SQLProspectUpdate & ""WHERE InternalRecordIdentifier = "" & txtInternalRecordIdentifier 'Response.write(SQLProspectUpdate & ""

    "") Set cnnProspectUpdate = Server.CreateObject(""ADODB.Connection"") cnnProspectUpdate.open (Session(""ClientCnnString"")) Set rsProspectUpdate = Server.CreateObject(""ADODB.Recordset"") rsProspectUpdate.CursorLocation = 3 Set rsProspectUpdate = cnnProspectUpdate.Execute(SQLProspectUpdate) Set rsProspectUpdate = Nothing cnnProspectUpdate.Close Set cnnProspectUpdate = Nothing '****************************************************** 'Update/Insert into PR_ProspectCompetitors '****************************************************** Set cnnProspectCompetitorCheck = Server.CreateObject(""ADODB.Connection"") cnnProspectCompetitorCheck.open (Session(""ClientCnnString"")) Set rsProspectCompetitorCheck = Server.CreateObject(""ADODB.Recordset"") rsProspectCompetitorCheck.CursorLocation = 3 SQLProspectCompetitorCheck = ""SELECT * FROM PR_ProspectCompetitors WHERE ProspectRecID = "" & txtInternalRecordIdentifier & "" AND PrimaryCompetitor = 1"" Set rsProspectCompetitorCheck = cnnProspectCompetitorCheck.Execute(SQLProspectCompetitorCheck) Response.Write(""
    "" & SQLProspectCompetitorCheck) '****************************************************************************************************************** 'CHECK TO SEE IF THIS PROSPECT HAS A PRIMARY COMPETITOR RECORD ALREADY 'THIS EDIT MODAL IS FOR ADDING/UPDATING A PRIMARY COMPETITOR ONLY, SO ALL CHECKS ARE BASED ON PRIMARY 'COMPETITOR FIELD '****************************************************************************************************************** If NOT rsProspectCompetitorCheck.EOF Then PrimaryCompetitorID = GetPrimaryCompetitorIDByProspectNumber(txtInternalRecordIdentifier) If PrimaryCompetitorID <> """" Then CurrentCompetitorName = GetCompetitorByNum(PrimaryCompetitorID) End If '*************************************************************************************************************** 'IF THIS PROSPECT HAS A PRIMARY COMPETITOR, WE WILL BE IN THIS BRANCH 'BECAUSE THEY ALREADY HAVE A PRIMARY COMPETITOR, WE NEED TO SEE IF THE COMPETITOR WAS CHANGED FROM THE ORIGINAL 'PRIMARY COMPETITOR THAT LOADED IN THE MODAL. '*************************************************************************************************************** If cInt(ORIG_CompetitorRecID) <> cInt(txtPrimaryCompetitor) Then '*************************************************************************************************************** 'IF THE PRIMARY COMPETITOR WAS CHANGED, WE HAVE TO CHECK AND SEE IF THIS COMPETITOR ALREADY EXISTS AS A 'COMPETITOR FOR THIS PROSPECT. IF IT DOES NOT EXIST AS A COMPETITOR FOR THIS PROSPECT, WE MUST ADD THIS 'COMPETITOR TO THIS PROSPECT VIA A SQL INSERT. IF THE NEW COMPETITOR SELECTED IS ALREADY A COMPETITOR FOR 'THIS PROSPECT, WE JUST UPDATE THE OFFERINGS. 'LASTLY, WE HAVE TO SET THIS NEW COMPETITOR TO BE THE PRIMARY COMPETITOR FOR THIS PROSPECT AND CHANGE ALL 'OTHER PRIMARY COMPETITORS FOR THIS PROSPECT TO 0 '*************************************************************************************************************** SQLProspectCompOfferingCheck = ""SELECT * FROM PR_ProspectCompetitors WHERE CompetitorRecID = "" & txtPrimaryCompetitor & "" AND ProspectRecID = "" & txtInternalRecordIdentifier Set cnnProspectCompOfferingCheck = Server.CreateObject(""ADODB.Connection"") cnnProspectCompOfferingCheck.open (Session(""ClientCnnString"")) Set rsProspectCompOfferingCheck = Server.CreateObject(""ADODB.Recordset"") rsProspectCompOfferingCheck.CursorLocation = 3 Set rsProspectCompOfferingCheck = cnnProspectCompOfferingCheck.Execute(SQLProspectCompOfferingCheck) If NOT rsProspectCompOfferingCheck.EOF Then SQLProspectCompOfferingUpdate = ""UPDATE PR_ProspectCompetitors SET BottledWater = "" & chkBottledWater & "", FilteredWater = "" & chkFilteredWater & "", OCS = "" & chkOCS & "", "" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & ""OCS_Supply = "" & chkOCS_Supply & "", Vending = "" & chkVending & "", MicroMarket = "" & chkMicroMarket & "", "" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & ""Pantry= "" & chkPantry & "", OfficeSupplies= "" & chkOfficeSupplies & "" "" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & "" WHERE CompetitorRecID = "" & txtPrimaryCompetitor & "" AND ProspectRecID = "" & txtInternalRecordIdentifier CompetitorName = GetCompetitorByNum(txtPrimaryCompetitor) '***************************************** 'AUDIT TRAIL ENTRIES '***************************************** If Orig_BottledWater <> chkBottledWater Then If (chkBottledWater = 1 OR chkBottledWater = vbTrue) Then Description = ""Bottled water was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Bottled water was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Bottled water was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Bottled water was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_FilteredWater <> chkFilteredWater Then If (chkFilteredWater = 1 OR chkFilteredWater = vbTrue) Then Description = ""Filtered water was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Filtered water was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Filtered water was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Filtered water was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OCS <> chkOCS Then If (chkOCS = 1 OR chkOCS = vbTrue) Then Description = ""OCS was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""OCS was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OCS_Supply <> chkOCS_Supply Then If (chkOCS_Supply = 1 OR chkOCS_Supply = vbTrue) Then Description = ""OCS Supply was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS Supply was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""OCS Supply was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS Supply was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OfficeSupplies <> chkOfficeSupplies Then If (chkOfficeSupplies = 1 OR chkOfficeSupplies = vbTrue) Then Description = ""Office Supplies was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Office Supplies was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Office Supplies was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Office Supplies was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Vending <> chkVending Then If (chkVending = 1 OR chkVending = vbTrue) Then Description = ""Vending was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Vending was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Vending was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Vending was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Micromarket <> chkMicromarket Then If (chkMicromarket = 1 OR chkMicromarket = vbTrue) Then Description = ""Micromarket was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Micromarket was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Micromarket was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Micromarket was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Pantry <> chkPantry Then If (chkPantry = 1 OR chkPantry = vbTrue) Then Description = ""Pantry was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Pantry was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Pantry was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Pantry was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If '***************************************** 'END AUDIT TRAIL ENTRIES '***************************************** Else SQLProspectCompOfferingUpdate = ""INSERT INTO PR_ProspectCompetitors (ProspectRecID, CompetitorRecID, PrimaryCompetitor, BottledWater, FilteredWater, "" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & "" OCS, OCS_Supply, Vending, MicroMarket, Pantry, OfficeSupplies) VALUES ("" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & txtInternalRecordIdentifier & "","" & txtPrimaryCompetitor & "",1, "" & chkBottledWater & "","" & chkFilteredWater & "", "" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & chkOCS & "","" & chkOCS_Supply & "","" & chkVending & "","" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & chkMicroMarket & "","" & chkPantry & "","" & chkOfficeSupplies & "")"" '***************************************** 'AUDIT TRAIL ENTRIES '***************************************** NewCompetitorName = GetCompetitorByNum(txtPrimaryCompetitor) Description = NewCompetitorName & "" was set to be the primary competitor for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" primary competitor change "",GetTerm(""Prospecting""),""Minor"",0,Description Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") If PrimaryCompetitorID <> """" Then Description = CurrentCompetitorName & "" was un-set as the primary competitor for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" primary competitor change "",GetTerm(""Prospecting""),""Minor"",0,Description Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If '***************************************** '***************************************** 'AUDIT TRAIL ENTRIES '***************************************** If Orig_BottledWater <> chkBottledWater Then If (chkBottledWater = 1 OR chkBottledWater = vbTrue) Then Description = ""Bottled water was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Bottled water was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Bottled water was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Bottled water was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_FilteredWater <> chkFilteredWater Then If (chkFilteredWater = 1 OR chkFilteredWater = vbTrue) Then Description = ""Filtered water was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Filtered water was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Filtered water was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Filtered water was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OCS <> chkOCS Then If (chkOCS = 1 OR chkOCS = vbTrue) Then Description = ""OCS was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""OCS was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OCS_Supply <> chkOCS_Supply Then If (chkOCS_Supply = 1 OR chkOCS_Supply = vbTrue) Then Description = ""OCS Supply was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS Supply was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""OCS Supply was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS Supply was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OfficeSupplies <> chkOfficeSupplies Then If (chkOfficeSupplies = 1 OR chkOfficeSupplies = vbTrue) Then Description = ""Office Supplies was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Office Supplies was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Office Supplies was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Office Supplies was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Vending <> chkVending Then If (chkVending = 1 OR chkVending = vbTrue) Then Description = ""Vending was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Vending was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Vending was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Vending was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Micromarket <> chkMicromarket Then If (chkMicromarket = 1 OR chkMicromarket = vbTrue) Then Description = ""Micromarket was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Micromarket was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Micromarket was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Micromarket was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Pantry <> chkPantry Then If (chkPantry = 1 OR chkPantry = vbTrue) Then Description = ""Pantry was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Pantry was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Pantry was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Pantry was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If '***************************************** End If Set rsProspectCompOfferingCheck = Nothing cnnProspectCompOfferingCheck.Close Set cnnProspectCompOfferingCheck = Nothing Response.write(""
    "" & SQLProspectCompOfferingUpdate) Set cnnProspectCompOfferingUpdate = Server.CreateObject(""ADODB.Connection"") cnnProspectCompOfferingUpdate.open (Session(""ClientCnnString"")) Set rsProspectCompOfferingUpdate = Server.CreateObject(""ADODB.Recordset"") rsProspectCompOfferingUpdate.CursorLocation = 3 Set rsProspectCompOfferingUpdate = cnnProspectCompOfferingUpdate.Execute(SQLProspectCompOfferingUpdate) SQLProspectCompOfferingUpdate = ""UPDATE PR_ProspectCompetitors SET PrimaryCompetitor = 0 WHERE ProspectRecID = "" & txtInternalRecordIdentifier & "" AND CompetitorRecID <> "" & txtPrimaryCompetitor Set rsProspectCompOfferingUpdate = cnnProspectCompOfferingUpdate.Execute(SQLProspectCompOfferingUpdate) Set rsProspectCompOfferingUpdate = Nothing cnnProspectCompOfferingUpdate.Close Set cnnProspectCompOfferingUpdate = Nothing Else '*************************************************************************************************************** 'THE CURRENT PRIMARY COMPETITOR WAS NOT CHANGED IN THE MODAL, SO WE JUST NEED TO UPDATE THE OFFERINGS 'FOR THE CURRENT PRIMARY COMPETITOR '*************************************************************************************************************** Set cnnProspectCompOfferingUpdate = Server.CreateObject(""ADODB.Connection"") cnnProspectCompOfferingUpdate.open (Session(""ClientCnnString"")) Set rsProspectCompOfferingUpdate = Server.CreateObject(""ADODB.Recordset"") rsProspectCompOfferingUpdate.CursorLocation = 3 SQLProspectCompOfferingUpdate = ""UPDATE PR_ProspectCompetitors SET BottledWater = "" & chkBottledWater & "", FilteredWater = "" & chkFilteredWater & "", OCS = "" & chkOCS & "", "" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & ""OCS_Supply = "" & chkOCS_Supply & "", Vending = "" & chkVending & "", MicroMarket = "" & chkMicroMarket & "", "" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & ""Pantry= "" & chkPantry & "", OfficeSupplies= "" & chkOfficeSupplies & "" "" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & "" WHERE CompetitorRecID = "" & txtPrimaryCompetitor & "" AND ProspectRecID = "" & txtInternalRecordIdentifier Set rsProspectCompOfferingUpdate = cnnProspectCompOfferingUpdate.Execute(SQLProspectCompOfferingUpdate) Set rsProspectCompOfferingUpdate = Nothing cnnProspectCompOfferingUpdate.Close Set cnnProspectCompOfferingUpdate = Nothing Response.write(""
    "" & SQLProspectCompOfferingUpdate) PrimaryCompetitorID = GetPrimaryCompetitorIDByProspectNumber(txtInternalRecordIdentifier) If PrimaryCompetitorID <> """" Then CompetitorName = GetCompetitorByNum(PrimaryCompetitorID) End If '***************************************** 'AUDIT TRAIL ENTRIES '***************************************** If Orig_BottledWater <> chkBottledWater Then If (chkBottledWater = 1 OR chkBottledWater = vbTrue) Then Description = ""Bottled water was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Bottled water was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Bottled water was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Bottled water was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_FilteredWater <> chkFilteredWater Then If (chkFilteredWater = 1 OR chkFilteredWater = vbTrue) Then Description = ""Filtered water was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Filtered water was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Filtered water was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Filtered water was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OCS <> chkOCS Then If (chkOCS = 1 OR chkOCS = vbTrue) Then Description = ""OCS was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""OCS was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OCS_Supply <> chkOCS_Supply Then If (chkOCS_Supply = 1 OR chkOCS_Supply = vbTrue) Then Description = ""OCS Supply was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS Supply was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""OCS Supply was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS Supply was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OfficeSupplies <> chkOfficeSupplies Then If (chkOfficeSupplies = 1 OR chkOfficeSupplies = vbTrue) Then Description = ""Office Supplies was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Office Supplies was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Office Supplies was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Office Supplies was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Vending <> chkVending Then If (chkVending = 1 OR chkVending = vbTrue) Then Description = ""Vending was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Vending was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Vending was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Vending was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Micromarket <> chkMicromarket Then If (chkMicromarket = 1 OR chkMicromarket = vbTrue) Then Description = ""Micromarket was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Micromarket was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Micromarket was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Micromarket was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Pantry <> chkPantry Then If (chkPantry = 1 OR chkPantry = vbTrue) Then Description = ""Pantry was added as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Pantry was added as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Pantry was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Pantry was removed as a competitor category being offered by the competitor "" & CompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If '***************************************** End If Else '*************************************************************************************************************** 'THIS PROSPECT HAD NO PRIMARY COMPETITOR PREVIOUSLY, SO IF THEY CHOSE A PRIMARY COMPETITOR IN THE EDIT MODAL, 'WE MUST PERFORM AN INSERT INTO PR_PROSPECTCOMPETITORS TABLE - NO UPDATE WILL EVER NEED TO HAPPEN '*************************************************************************************************************** If cInt(txtPrimaryCompetitor) <> 0 Then Set cnnProspectCompOfferingUpdate = Server.CreateObject(""ADODB.Connection"") cnnProspectCompOfferingUpdate.open (Session(""ClientCnnString"")) Set rsProspectCompOfferingUpdate = Server.CreateObject(""ADODB.Recordset"") rsProspectCompOfferingUpdate.CursorLocation = 3 SQLProspectCompOfferingUpdate = ""INSERT INTO PR_ProspectCompetitors (ProspectRecID, CompetitorRecID, PrimaryCompetitor, BottledWater, FilteredWater, "" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & "" OCS, OCS_Supply, Vending, MicroMarket, Pantry, OfficeSupplies) VALUES ("" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & txtInternalRecordIdentifier & "","" & txtPrimaryCompetitor & "",1,"" & chkBottledWater & "","" & chkFilteredWater & "", "" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & chkOCS & "","" & chkOCS_Supply & "","" & chkVending & "","" SQLProspectCompOfferingUpdate = SQLProspectCompOfferingUpdate & chkMicroMarket & "","" & chkPantry & "","" & chkOfficeSupplies & "")"" Response.write(""
    "" & SQLProspectCompOfferingUpdate) Set rsProspectCompOfferingUpdate = cnnProspectCompOfferingUpdate.Execute(SQLProspectCompOfferingUpdate) Set rsProspectCompOfferingUpdate = Nothing cnnProspectCompOfferingUpdate.Close Set cnnProspectCompOfferingUpdate = Nothing '***************************************** 'AUDIT TRAIL ENTRIES '***************************************** NewCompetitorName = GetCompetitorByNum(txtPrimaryCompetitor) Description = NewCompetitorName & "" was set to be the primary competitor for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" primary competitor change "",GetTerm(""Prospecting""),""Minor"",0,Description Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") If Orig_BottledWater <> chkBottledWater Then If (chkBottledWater = 1 OR chkBottledWater = vbTrue) Then Description = ""Bottled water was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Bottled water was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Bottled water was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Bottled water was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_FilteredWater <> chkFilteredWater Then If (chkFilteredWater = 1 OR chkFilteredWater = vbTrue) Then Description = ""Filtered water was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Filtered water was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Filtered water was removed as a competitor category being offered by the competitor "" & CompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Filtered water was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OCS <> chkOCS Then If (chkOCS = 1 OR chkOCS = vbTrue) Then Description = ""OCS was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""OCS was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OCS_Supply <> chkOCS_Supply Then If (chkOCS_Supply = 1 OR chkOCS_Supply = vbTrue) Then Description = ""OCS Supply was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS Supply was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""OCS Supply was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""OCS Supply was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_OfficeSupplies <> chkOfficeSupplies Then If (chkOfficeSupplies = 1 OR chkOfficeSupplies = vbTrue) Then Description = ""Office Supplies was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Office Supplies was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Office Supplies was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Office Supplies was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Vending <> chkVending Then If (chkVending = 1 OR chkVending = vbTrue) Then Description = ""Vending was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Vending was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Vending was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Vending was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Micromarket <> chkMicromarket Then If (chkMicromarket = 1 OR chkMicromarket = vbTrue) Then Description = ""Micromarket was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Micromarket was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Micromarket was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Micromarket was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If If Orig_Pantry <> chkPantry Then If (chkPantry = 1 OR chkPantry = vbTrue) Then Description = ""Pantry was added as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Pantry was added as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") Else Description = ""Pantry was removed as a competitor category being offered by the competitor "" & NewCompetitorName & "" for the prospect "" & GetProspectNameByNumber(txtInternalRecordIdentifier) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"")& "" competitor category offering change "",GetTerm(""Prospecting""),""Minor"",0,Description Description = ""Pantry was removed as a competitor category being offered by the competitor "" & NewCompetitorName Record_PR_Activity txtInternalRecordIdentifier, Description, Session(""UserNo"") End If End If '***************************************** 'End Audit Trail Entries '***************************************** End If End If Set rsProspectCompetitorCheck = Nothing cnnProspectCompetitorCheck.Close Set cnnProspectCompetitorCheck = Nothing '******************************************************************************************************************* '******************************************************************************************************************* 'PERFORM AUDIT LOG UPDATE ENTRIES '******************************************************************************************************************* If cInt(ORIG_TelemarketerUserNo) = 0 AND cInt(txtTelemarketerUserNo) <> 0 AND (cInt(ORIG_TelemarketerUserNo) <> cInt(txtTelemarketerUserNo)) Then Description = ""The telemarketer for prospect "" & ProspectName & "" was changed to "" & GetUserDisplayNameByUserNo(txtTelemarketerUserNo) & "" from No Telemarketer Selected by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"") & "" prospect telemarketer changed"",GetTerm(""Prospecting"") & "" prospect telemarketer changed"",""Major"",0,Description Record_PR_Activity txtInternalRecordIdentifier,Description,Session(""UserNo"") ElseIf cInt(ORIG_TelemarketerUserNo) <> 0 AND cInt(txtTelemarketerUserNo) = 0 AND (cInt(ORIG_TelemarketerUserNo) <> cInt(txtTelemarketerUserNo)) Then Description = ""The telemarketer for prospect "" & ProspectName & "" was changed to No Telemarketer Selected from "" & GetUserDisplayNameByUserNo(ORIG_TelemarketerUserNo) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"") & "" prospect telemarketer changed"",GetTerm(""Prospecting"") & "" prospect telemarketer changed"",""Major"",0,Description Record_PR_Activity txtInternalRecordIdentifier,Description,Session(""UserNo"") ElseIf cInt(ORIG_TelemarketerUserNo) <> cInt(txtTelemarketerUserNo) Then Description = ""The telemarketer for prospect "" & ProspectName & "" was changed to "" & GetUserDisplayNameByUserNo(txtTelemarketerUserNo) & "" from "" & GetUserDisplayNameByUserNo(ORIG_TelemarketerUserNo) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"") & "" prospect telemarketer changed"",GetTerm(""Prospecting"") & "" prospect telemarketer changed"",""Major"",0,Description Record_PR_Activity txtInternalRecordIdentifier,Description,Session(""UserNo"") End If If cInt(ORIG_LeadSourceNumber) = 0 AND cInt(txtLeadSourceNumber) <> 0 AND (cInt(ORIG_LeadSourceNumber) <> cInt(txtLeadSourceNumber)) Then Description = ""The lead source for prospect "" & ProspectName & "" was changed to "" & GetLeadSourceByNum(txtLeadSourceNumber) & "" from No Telemarketer Selected by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"") & "" prospect lead source changed"",GetTerm(""Prospecting"") & "" prospect lead source changed"",""Major"",0,Description Record_PR_Activity txtInternalRecordIdentifier,Description,Session(""UserNo"") ElseIf cInt(ORIG_LeadSourceNumber) <> 0 AND cInt(txtLeadSourceNumber) = 0 AND (cInt(ORIG_LeadSourceNumber) <> cInt(txtLeadSourceNumber)) Then Description = ""The lead source for prospect "" & ProspectName & "" was changed to No Telemarketer Selected from "" & GetLeadSourceByNum(ORIG_LeadSourceNumber) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"") & "" prospect lead source changed"",GetTerm(""Prospecting"") & "" prospect lead source changed"",""Major"",0,Description Record_PR_Activity txtInternalRecordIdentifier,Description,Session(""UserNo"") ElseIf cInt(ORIG_LeadSourceNumber) <> cInt(txtLeadSourceNumber) Then Description = ""The lead source for prospect "" & ProspectName & "" was changed to "" & GetLeadSourceByNum(txtLeadSourceNumber) & "" from "" & GetLeadSourceByNum(ORIG_LeadSourceNumber) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"") & "" prospect lead source changed"",GetTerm(""Prospecting"") & "" prospect lead source changed"",""Major"",0,Description Record_PR_Activity txtInternalRecordIdentifier,Description,Session(""UserNo"") End If If ORIG_FormerCustNum = """" OR IsNull(ORIG_FormerCustNum) Then ORIG_FormerCustNum = ""NONE ENTERED"" If txtFormerCustomerNumber = """" Then txtFormerCustomerNumber = ""NONE ENTERED"" If ORIG_FormerCustNum <> txtFormerCustomerNumber Then Description = ""The former customer number for prospect "" & ProspectName & "" was changed to "" & txtFormerCustomerNumber & "" from "" & ORIG_FormerCustNum & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"") & "" prospect former customer number changed"",GetTerm(""Prospecting"") & "" prospect former customer number changed"",""Major"",0,Description Record_PR_Activity txtInternalRecordIdentifier,Description,Session(""UserNo"") End If 'Response.write(""ORIG_FormerCustomerCancelDate: "" & ORIG_FormerCustomerCancelDate & ""
    "") 'Response.write(""txtFormerCustomerCancelDate : "" & txtFormerCustomerCancelDate & ""
    "") If ORIG_FormerCustomerCancelDate = """" OR IsNull(ORIG_FormerCustomerCancelDate) Then ORIG_FormerCustomerCancelDate = ""NONE ENTERED"" If txtFormerCustomerCancelDate = """" Then txtFormerCustomerCancelDate = ""NONE ENTERED"" If ORIG_FormerCustomerCancelDate <> """" AND ORIG_FormerCustomerCancelDate <> ""NONE ENTERED"" Then If cDate(ORIG_FormerCustomerCancelDate) = ""1/1/1900"" Then ORIG_FormerCustomerCancelDate = ""NONE ENTERED"" End If End If If ORIG_FormerCustomerCancelDate <> txtFormerCustomerCancelDate Then If ORIG_FormerCustomerCancelDate <> ""NONE ENTERED"" AND txtFormerCustomerCancelDate <> ""NONE ENTERED"" Then If DateDiff(""d"",cDate(ORIG_FormerCustomerCancelDate),cDate(txtFormerCustomerCancelDate)) <> 0 Then Description = ""The former customer cancel date for prospect "" & ProspectName & "" was changed to "" & formatDateTime(txtFormerCustomerCancelDate,2) & "" from "" & formatDateTime(ORIG_FormerCustomerCancelDate,2) & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"") & "" prospect former customer cancel date changed"",GetTerm(""Prospecting"") & "" prospect former customer cancel date changed"",""Major"",0,Description Record_PR_Activity txtInternalRecordIdentifier,Description,Session(""UserNo"") End If Else Description = ""The former customer cancel date for prospect "" & ProspectName & "" was changed to "" & txtFormerCustomerCancelDate & "" from "" & ORIG_FormerCustomerCancelDate & "" by "" & GetUserDisplayNameByUserNo(Session(""UserNo"")) CreateAuditLogEntry GetTerm(""Prospecting"") & "" prospect former customer cancel date changed"",GetTerm(""Prospecting"") & "" prospect former customer cancel date changed"",""Major"",0,Description Record_PR_Activity txtInternalRecordIdentifier,Description,Session(""UserNo"") End If End If '******************************************************************************************************************* Response.Redirect (""viewProspectDetail.asp?i="" & txtInternalRecordIdentifier) %>",16197,True,4560.486512359746,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * When false, CREATE TABLE syntax without a provider will use * the value of spark.sql.sources.default as its provider. */ public boolean legacy_create_hive_table_by_default_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE namespace (IF NOT EXISTS)? multipartIdentifier (commentSpec | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER namespace multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER namespace multipartIdentifier SET locationSpec #setNamespaceLocation | DROP namespace (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | {!legacy_create_hive_table_by_default_enabled}? createTableHeader ('(' colTypeList ')')? tableProvider? createTableClauses (AS? query)? #createTable | {legacy_create_hive_table_by_default_enabled}? createTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (commentSpec | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties |ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier alterColumnAction? #alterTableAlterColumn | ALTER TABLE table=multipartIdentifier partitionSpec? CHANGE COLUMN? colName=multipartIdentifier colType colPosition? #hiveChangeColumn | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? (commentSpec | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) ns=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) ns=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier (AS SERDE)? #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) namespace EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeRelation | (DESC | DESCRIBE) QUERY? query #describeQuery | COMMENT ON namespace multipartIdentifier IS comment=(STRING | NULL) #commentNamespace | COMMENT ON TABLE multipartIdentifier IS comment=(STRING | NULL) #commentTable | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier (STRING | .*?) #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; commentSpec : COMMENT STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; namespace : NAMESPACE | DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; createTableClauses :((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | commentSpec | (TBLPROPERTIES tableProps=tablePropertyList))* ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier commentSpec? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=RLIKE pattern=valueExpression | NOT? kind=LIKE pattern=valueExpression (ESCAPE escapeChar=STRING)? | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | FIRST '(' expression (IGNORE NULLS)? ')' #first | LAST '(' expression (IGNORE NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (FILTER '(' WHERE where=booleanExpression ')')? (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | HOUR | MINUTE | MONTH | SECOND | YEAR | identifier ; colPosition : position=FIRST | position=AFTER afterCol=errorCapturingIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (NOT NULL)? commentSpec? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (NOT NULL)? commentSpec? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (NOT NULL)? commentSpec? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | FILTER | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; alterColumnAction : TYPE dataType | commentSpec | colPosition | setOrDrop=(SET | DROP) NOT NULL ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `EXPLAIN SELECT ...` is a command, but EXPLAIN // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WINDOW ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPE | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FILTER | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MINUTE | MONTH | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WHEN | WHERE | WINDOW | WITH | YEAR ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILTER: 'FILTER'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12364,False,2321.1728797880055,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; /** * This method will be called when we see '/*' and try to match it as a bracketed comment. * If the next character is '+', it should be parsed as hint later, and we cannot match * it as a bracketed comment. * * Returns true if the next character is '+'. */ public boolean isHint() { int nextChar = _input.LA(1); if (nextChar == '+') { return true; } else { return false; } } } singleStatement : statement ';'* EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE namespace (IF NOT EXISTS)? multipartIdentifier (commentSpec | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER namespace multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER namespace multipartIdentifier SET locationSpec #setNamespaceLocation | DROP namespace (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (commentSpec | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier alterColumnAction? #alterTableAlterColumn | ALTER TABLE table=multipartIdentifier partitionSpec? CHANGE COLUMN? colName=multipartIdentifier colType colPosition? #hiveChangeColumn | ALTER TABLE table=multipartIdentifier partitionSpec? REPLACE COLUMNS '(' columns=qualifiedColTypeWithPositionList ')' #hiveReplaceColumns | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? (commentSpec | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) ns=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) ns=multipartIdentifier)? #showColumns | SHOW VIEWS ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showViews | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier (AS SERDE)? #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) namespace EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeRelation | (DESC | DESCRIBE) QUERY? query #describeQuery | COMMENT ON namespace multipartIdentifier IS comment=(STRING | NULL) #commentNamespace | COMMENT ON TABLE multipartIdentifier IS comment=(STRING | NULL) #commentTable | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier (STRING | .*?) #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; commentSpec : COMMENT STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; namespace : NAMESPACE | DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; createTableClauses :((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | commentSpec | (TBLPROPERTIES tableProps=tablePropertyList))* ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier commentSpec? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=RLIKE pattern=valueExpression | NOT? kind=LIKE quantifier=(ANY | SOME | ALL) ('('')' | '(' expression (',' expression)* ')') | NOT? kind=LIKE pattern=valueExpression (ESCAPE escapeChar=STRING)? | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | FIRST '(' expression (IGNORE NULLS)? ')' #first | LAST '(' expression (IGNORE NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (FILTER '(' WHERE where=booleanExpression ')')? (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | HOUR | MINUTE | MONTH | SECOND | YEAR | identifier ; colPosition : position=FIRST | position=AFTER afterCol=errorCapturingIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (NOT NULL)? commentSpec? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (NOT NULL)? commentSpec? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (NOT NULL)? commentSpec? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | FILTER | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; alterColumnAction : TYPE dataType | commentSpec | colPosition | setOrDrop=(SET | DROP) NOT NULL ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `EXPLAIN SELECT ...` is a command, but EXPLAIN // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | VIEWS | WINDOW ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPE | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FILTER | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MINUTE | MONTH | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | VIEWS | WHEN | WHERE | WINDOW | WITH | YEAR ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILTER: 'FILTER'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; VIEWS: 'VIEWS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ('\\\\\\n' | ~[\\r\\n])* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' {!isHint()}? (BRACKETED_COMMENT|.)*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12483,False,2340.946596360349,median "<%-- // // DefaultWsdlHelpGenerator.aspx: // // Author: // Lluis Sanchez Gual (lluis@ximian.com) // // (C) 2003 Ximian, Inc. http://www.ximian.com // --%> <%@ Import Namespace=""System.Collections"" %> <%@ Import Namespace=""System.IO"" %> <%@ Import Namespace=""System.Xml.Serialization"" %> <%@ Import Namespace=""System.Xml"" %> <%@ Import Namespace=""System.Xml.Schema"" %> <%@ Import Namespace=""System.Web.Services.Description"" %> <%@ Import Namespace=""System"" %> <%@ Import Namespace=""System.Net"" %> <%@ Import Namespace=""System.Globalization"" %> <%@ Import Namespace=""System.Resources"" %> <%@ Import Namespace=""System.Diagnostics"" %> <%@ Import Namespace=""System.CodeDom"" %> <%@ Import Namespace=""System.CodeDom.Compiler"" %> <%@ Import Namespace=""Microsoft.CSharp"" %> <%@ Import Namespace=""Microsoft.VisualBasic"" %> <%@ Import Namespace=""System.Text"" %> <%@ Import Namespace=""System.Text.RegularExpressions"" %> <%@ Import Namespace=""System.Security.Cryptography.X509Certificates"" %> <%@ Assembly name=""System.Web.Services"" %> <%@ Page debug=""true"" %> ?disco""/> <%=WebServiceName%> Web Service
    Web Service
    <%=WebServiceName%>
    Overview
    Service Description
    Client proxy

    <%#FormatBindingName(DataBinder.Eval(Container.DataItem, ""Name"").ToString())%> ?<%=GetTabContext(""op"",null)%>op=<%#GetOpName(Container.DataItem)%>&bnd=<%#DataBinder.Eval(Container.DataItem, ""Binding.Name"")%>""><%#GetOpName(Container.DataItem)%>

    <% if (CurrentPage == ""main"") {%>

    Web Service Overview

    <%=WebServiceDescription%> <%} if (DefaultBinding == null) {%> This service does not contain any public web method. <%} else if (CurrentPage == ""op"") {%> <%=CurrentOperationName%>

    <% WriteTabs (); %>


    <% if (CurrentTab == ""main"") { %> Input Parameters
    <% if (InParams.Count == 0) { %> No input parameters
    <% } else { %>
    <%#DataBinder.Eval(Container.DataItem, ""Name"")%> <%#DataBinder.Eval(Container.DataItem, ""Type"")%>
    <% } %>
    <% if (OutParams.Count > 0) { %> Output Parameters
    <%#DataBinder.Eval(Container.DataItem, ""Name"")%> <%#DataBinder.Eval(Container.DataItem, ""Type"")%>

    <% } %> Remarks
    <%=OperationDocumentation%>

    Technical information
    Format: <%=CurrentOperationFormat%>
    Supported protocols: <%=CurrentOperationProtocols%> <% } %> <% if (CurrentTab == ""test"") { if (CurrentOperationSupportsTest) {%> Enter values for the parameters and click the 'Invoke' button to test this method:

    "" method=""GET""> ""> ""> ""> "">
    <%#DataBinder.Eval(Container.DataItem, ""Name"")%>:  "">
     
    ""> The web service returned the following result:

    <%=GetTestResult()%>
    <% } else {%> The test form is not available for this operation because it has parameters with a complex structure. <% } %> <% } %> <% if (CurrentTab == ""msg"") { %> The following are sample SOAP requests and responses for each protocol supported by this method:

    <% if (IsOperationSupported (""Soap"")) { %> Soap

    <%=GenerateOperationMessages (""Soap"", true)%>

    <%=GenerateOperationMessages (""Soap"", false)%>

    <% } %> <% if (IsOperationSupported (""HttpGet"")) { %> HTTP Get

    <%=GenerateOperationMessages (""HttpGet"", true)%>

    <%=GenerateOperationMessages (""HttpGet"", false)%>

    <% } %> <% if (IsOperationSupported (""HttpPost"")) { %> HTTP Post

    <%=GenerateOperationMessages (""HttpPost"", true)%>

    <%=GenerateOperationMessages (""HttpPost"", false)%>

    <% } %> <% } %> <%} else if (CurrentPage == ""proxy"") {%>
    "" name=""langForm"" method=""GET""> Select the language for which you want to generate a proxy "">    

    <%=CurrentProxytName%>    "">Download

    ""><%=GetProxyCode ()%>
    <%} else if (CurrentPage == ""wsdl"") {%> <% if (descriptions.Count > 1 || schemas.Count > 1) {%> The description of this web service is composed by several documents. Click on the document you want to see: <%} else {%> <%}%>
    <%=CurrentDocumentName%>    "">Download

    <%=GenerateDocument ()%>
    <%}%>














    ",16306,True,2551.9796203245382,median "/* * [The ""MIT license""] Copyright © 2014 Sam Harwell, Tunnel Vision Laboratories, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the ""Software""), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * 1. The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. 2. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. 3. Except as contained in this notice, the name of Tunnel Vision * Laboratories, LLC. shall not be used in advertising or otherwise to promote the sale, use or * other dealings in this Software without prior written authorization from Tunnel Vision * Laboratories, LLC. */ lexer grammar PostgreSqlLexer; /* Reference: http://www.postgresql.org/docs/9.3/static/sql-syntax-lexical.html */ @header { import java.util.ArrayDeque; import java.util.Deque; } @members { /* This field stores the tags which are used to detect the end of a dollar-quoted string literal. */ private final Deque _tags = new ArrayDeque(); } // // SPECIAL CHARACTERS (§4.1.4) // // // Note that Asterisk is a valid operator, but does not have the type Operator due to its syntactic // use in locations that are not expressions. Dollar: '$'; LeftParen: '('; RightParen: ')'; LeftBracket: '['; RightBracket: ']'; Comma: ','; Semicolon: ';'; Colon: ':'; Asterisk: '*'; Equal: '='; Period: '.'; NamedArgument: ':='; // // OPERATORS (§4.1.3) // // // this rule does not allow + or - at the end of a multi-character operator Operator: ( OperatorCharacter | ('+' | '-' {_input.LA(1) != '-'}?)+ ( OperatorCharacter | '/' {_input.LA(1) != '*'}? ) | '/' {_input.LA(1) != '*'}? )+ | // special handling for the single-character operators + and - [+-]; /* This rule handles operators which end with + or -, and sets the token type to Operator. It is * comprised of four parts, in order: * * 1. A prefix, which does not contain a character from the required set which allows + or - to * appear at the end of the operator. 2. A character from the required set which allows + or - to * appear at the end of the operator. 3. An optional sub-token which takes the form of an operator * which does not include a + or - at the end of the sub-token. 4. A suffix sequence of + and - * characters. */ OperatorEndingWithPlusMinus: ( OperatorCharacterNotAllowPlusMinusAtEnd | '-' {_input.LA(1) != '-'}? | '/' {_input.LA(1) != '*'}? )* OperatorCharacterAllowPlusMinusAtEnd Operator? ( '+' | '-' {_input.LA(1) != '-'}? )+ -> type(Operator); // Each of the following fragment rules omits the +, -, and / characters, which must always be // handled in a special way by the operator rules above. fragment OperatorCharacter: [*<>=~!@#%^&|`?]; // these are the operator characters that don't count towards one ending with + or - fragment OperatorCharacterNotAllowPlusMinusAtEnd: [*<>=+]; // an operator may end with + or - if it contains one of these characters fragment OperatorCharacterAllowPlusMinusAtEnd: [~!@#%^&|`?]; // // KEYWORDS (Appendix C) // // // // reserved keywords // // ALL: [Aa][Ll][Ll]; ANALYSE: [Aa][Nn][Aa][Ll][Yy][Ss][Ee]; ANALYZE: [Aa][Nn][Aa][Ll][Yy][Zz][Ee]; AND: [Aa][Nn][Dd]; ANY: [Aa][Nn][Yy]; ARRAY: [Aa][Rr][Rr][Aa][Yy]; AS: [Aa][Ss]; ASC: [Aa][Ss][Cc]; ASYMMETRIC: [Aa][Ss][Yy][Mm][Mm][Ee][Tt][Rr][Ii][Cc]; BOTH: [Bb][Oo][Tt][Hh]; CASE: [Cc][Aa][Ss][Ee]; CAST: [Cc][Aa][Ss][Tt]; CHECK: [Cc][Hh][Ee][Cc][Kk]; COLLATE: [Cc][Oo][Ll][Ll][Aa][Tt][Ee]; COLUMN: [Cc][Oo][Ll][Uu][Mm][Nn]; CONSTRAINT: [Cc][Oo][Nn][Ss][Tt][Rr][Aa][Ii][Nn][Tt]; CREATE: [Cc][Rr][Ee][Aa][Tt][Ee]; CURRENT_CATALOG: [Cc][Uu][Rr][Rr][Ee][Nn][Tt][_][Cc][Aa][Tt][Aa][Ll][Oo][Gg]; CURRENT_DATE: [Cc][Uu][Rr][Rr][Ee][Nn][Tt][_][Dd][Aa][Tt][Ee]; CURRENT_ROLE: [Cc][Uu][Rr][Rr][Ee][Nn][Tt][_][Rr][Oo][Ll][Ee]; CURRENT_TIME: [Cc][Uu][Rr][Rr][Ee][Nn][Tt][_][Tt][Ii][Mm][Ee]; CURRENT_TIMESTAMP: [Cc][Uu][Rr][Rr][Ee][Nn][Tt][_][Tt][Ii][Mm][Ee][Ss][Tt][Aa][Mm][Pp]; CURRENT_USER: [Cc][Uu][Rr][Rr][Ee][Nn][Tt][_][Uu][Ss][Ee][Rr]; DEFAULT: [Dd][Ee][Ff][Aa][Uu][Ll][Tt]; DEFERRABLE: [Dd][Ee][Ff][Ee][Rr][Rr][Aa][Bb][Ll][Ee]; DESC: [Dd][Ee][Ss][Cc]; DISTINCT: [Dd][Ii][Ss][Tt][Ii][Nn][Cc][Tt]; DO: [Dd][Oo]; ELSE: [Ee][Ll][Ss][Ee]; END: [Ee][Nn][Dd]; EXCEPT: [Ee][Xx][Cc][Ee][Pp][Tt]; FALSE: [Ff][Aa][Ll][Ss][Ee]; FETCH: [Ff][Ee][Tt][Cc][Hh]; FOR: [Ff][Oo][Rr]; FOREIGN: [Ff][Oo][Rr][Ee][Ii][Gg][Nn]; FROM: [Ff][Rr][Oo][Mm]; GRANT: [Gg][Rr][Aa][Nn][Tt]; GROUP: [Gg][Rr][Oo][Uu][Pp]; HAVING: [Hh][Aa][Vv][Ii][Nn][Gg]; IN: [Ii][Nn]; INITIALLY: [Ii][Nn][Ii][Tt][Ii][Aa][Ll][Ll][Yy]; INTERSECT: [Ii][Nn][Tt][Ee][Rr][Ss][Ee][Cc][Tt]; INTO: [Ii][Nn][Tt][Oo]; LATERAL: [Ll][Aa][Tt][Ee][Rr][Aa][Ll]; LEADING: [Ll][Ee][Aa][Dd][Ii][Nn][Gg]; LIMIT: [Ll][Ii][Mm][Ii][Tt]; LOCALTIME: [Ll][Oo][Cc][Aa][Ll][Tt][Ii][Mm][Ee]; LOCALTIMESTAMP: [Ll][Oo][Cc][Aa][Ll][Tt][Ii][Mm][Ee][Ss][Tt][Aa][Mm][Pp]; NOT: [Nn][Oo][Tt]; NULL: [Nn][Uu][Ll][Ll]; OFFSET: [Oo][Ff][Ff][Ss][Ee][Tt]; ON: [Oo][Nn]; ONLY: [Oo][Nn][Ll][Yy]; OR: [Oo][Rr]; ORDER: [Oo][Rr][Dd][Ee][Rr]; PLACING: [Pp][Ll][Aa][Cc][Ii][Nn][Gg]; PRIMARY: [Pp][Rr][Ii][Mm][Aa][Rr][Yy]; REFERENCES: [Rr][Ee][Ff][Ee][Rr][Ee][Nn][Cc][Ee][Ss]; RETURNING: [Rr][Ee][Tt][Uu][Rr][Nn][Ii][Nn][Gg]; SELECT: [Ss][Ee][Ll][Ee][Cc][Tt]; SESSION_USER: [Ss][Ee][Ss][Ss][Ii][Oo][Nn][_][Uu][Ss][Ee][Rr]; SOME: [Ss][Oo][Mm][Ee]; SYMMETRIC: [Ss][Yy][Mm][Mm][Ee][Tt][Rr][Ii][Cc]; TABLE: [Tt][Aa][Bb][Ll][Ee]; THEN: [Tt][Hh][Ee][Nn]; TO: [Tt][Oo]; TRAILING: [Tt][Rr][Aa][Ii][Ll][Ii][Nn][Gg]; TRUE: [Tt][Rr][Uu][Ee]; UNION: [Uu][Nn][Ii][Oo][Nn]; UNIQUE: [Uu][Nn][Ii][Qq][Uu][Ee]; USER: [Uu][Ss][Ee][Rr]; USING: [Uu][Ss][Ii][Nn][Gg]; VARIADIC: [Vv][Aa][Rr][Ii][Aa][Dd][Ii][Cc]; WHEN: [Ww][Hh][Ee][Nn]; WHERE: [Ww][Hh][Ee][Rr][Ee]; WINDOW: [Ww][Ii][Nn][Dd][Oo][Ww]; WITH: [Ww][Ii][Tt][Hh]; // // reserved keywords (can be function or type) // // AUTHORIZATION: [Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn]; BINARY: [Bb][Ii][Nn][Aa][Rr][Yy]; COLLATION: [Cc][Oo][Ll][Ll][Aa][Tt][Ii][Oo][Nn]; CONCURRENTLY: [Cc][Oo][Nn][Cc][Uu][Rr][Rr][Ee][Nn][Tt][Ll][Yy]; CROSS: [Cc][Rr][Oo][Ss][Ss]; CURRENT_SCHEMA: [Cc][Uu][Rr][Rr][Ee][Nn][Tt][_][Ss][Cc][Hh][Ee][Mm][Aa]; FREEZE: [Ff][Rr][Ee][Ee][Zz][Ee]; FULL: [Ff][Uu][Ll][Ll]; ILIKE: [Ii][Ll][Ii][Kk][Ee]; INNER: [Ii][Nn][Nn][Ee][Rr]; IS: [Ii][Ss]; ISNULL: [Ii][Ss][Nn][Uu][Ll][Ll]; JOIN: [Jj][Oo][Ii][Nn]; LEFT: [Ll][Ee][Ff][Tt]; LIKE: [Ll][Ii][Kk][Ee]; NATURAL: [Nn][Aa][Tt][Uu][Rr][Aa][Ll]; NOTNULL: [Nn][Oo][Tt][Nn][Uu][Ll][Ll]; OUTER: [Oo][Uu][Tt][Ee][Rr]; OVER: [Oo][Vv][Ee][Rr]; OVERLAPS: [Oo][Vv][Ee][Rr][Ll][Aa][Pp][Ss]; RIGHT: [Rr][Ii][Gg][Hh][Tt]; SIMILAR: [Ss][Ii][Mm][Ii][Ll][Aa][Rr]; VERBOSE: [Vv][Ee][Rr][Bb][Oo][Ss][Ee]; // // non-reserved keywords // // ABORT: [Aa][Bb][Oo][Rr][Tt]; ABSOLUTE: [Aa][Bb][Ss][Oo][Ll][Uu][Tt][Ee]; ACCESS: [Aa][Cc][Cc][Ee][Ss][Ss]; ACTION: [Aa][Cc][Tt][Ii][Oo][Nn]; ADD: [Aa][Dd][Dd]; ADMIN: [Aa][Dd][Mm][Ii][Nn]; AFTER: [Aa][Ff][Tt][Ee][Rr]; AGGREGATE: [Aa][Gg][Gg][Rr][Ee][Gg][Aa][Tt][Ee]; ALSO: [Aa][Ll][Ss][Oo]; ALTER: [Aa][Ll][Tt][Ee][Rr]; ALWAYS: [Aa][Ll][Ww][Aa][Yy][Ss]; ASSERTION: [Aa][Ss][Ss][Ee][Rr][Tt][Ii][Oo][Nn]; ASSIGNMENT: [Aa][Ss][Ss][Ii][Gg][Nn][Mm][Ee][Nn][Tt]; AT: [Aa][Tt]; ATTRIBUTE: [Aa][Tt][Tt][Rr][Ii][Bb][Uu][Tt][Ee]; BACKWARD: [Bb][Aa][Cc][Kk][Ww][Aa][Rr][Dd]; BEFORE: [Bb][Ee][Ff][Oo][Rr][Ee]; BEGIN: [Bb][Ee][Gg][Ii][Nn]; BY: [Bb][Yy]; CACHE: [Cc][Aa][Cc][Hh][Ee]; CALLED: [Cc][Aa][Ll][Ll][Ee][Dd]; CASCADE: [Cc][Aa][Ss][Cc][Aa][Dd][Ee]; CASCADED: [Cc][Aa][Ss][Cc][Aa][Dd][Ee][Dd]; CATALOG: [Cc][Aa][Tt][Aa][Ll][Oo][Gg]; CHAIN: [Cc][Hh][Aa][Ii][Nn]; CHARACTERISTICS: [Cc][Hh][Aa][Rr][Aa][Cc][Tt][Ee][Rr][Ii][Ss][Tt][Ii][Cc][Ss]; CHECKPOINT: [Cc][Hh][Ee][Cc][Kk][Pp][Oo][Ii][Nn][Tt]; CLASS: [Cc][Ll][Aa][Ss][Ss]; CLOSE: [Cc][Ll][Oo][Ss][Ee]; CLUSTER: [Cc][Ll][Uu][Ss][Tt][Ee][Rr]; COMMENT: [Cc][Oo][Mm][Mm][Ee][Nn][Tt]; COMMENTS: [Cc][Oo][Mm][Mm][Ee][Nn][Tt][Ss]; COMMIT: [Cc][Oo][Mm][Mm][Ii][Tt]; COMMITTED: [Cc][Oo][Mm][Mm][Ii][Tt][Tt][Ee][Dd]; CONFIGURATION: [Cc][Oo][Nn][Ff][Ii][Gg][Uu][Rr][Aa][Tt][Ii][Oo][Nn]; CONNECTION: [Cc][Oo][Nn][Nn][Ee][Cc][Tt][Ii][Oo][Nn]; CONSTRAINTS: [Cc][Oo][Nn][Ss][Tt][Rr][Aa][Ii][Nn][Tt][Ss]; CONTENT: [Cc][Oo][Nn][Tt][Ee][Nn][Tt]; CONTINUE: [Cc][Oo][Nn][Tt][Ii][Nn][Uu][Ee]; CONVERSION: [Cc][Oo][Nn][Vv][Ee][Rr][Ss][Ii][Oo][Nn]; COPY: [Cc][Oo][Pp][Yy]; COST: [Cc][Oo][Ss][Tt]; CSV: [Cc][Ss][Vv]; CURRENT: [Cc][Uu][Rr][Rr][Ee][Nn][Tt]; CURSOR: [Cc][Uu][Rr][Ss][Oo][Rr]; CYCLE: [Cc][Yy][Cc][Ll][Ee]; DATA: [Dd][Aa][Tt][Aa]; DATABASE: [Dd][Aa][Tt][Aa][Bb][Aa][Ss][Ee]; DAY: [Dd][Aa][Yy]; DEALLOCATE: [Dd][Ee][Aa][Ll][Ll][Oo][Cc][Aa][Tt][Ee]; DECLARE: [Dd][Ee][Cc][Ll][Aa][Rr][Ee]; DEFAULTS: [Dd][Ee][Ff][Aa][Uu][Ll][Tt][Ss]; DEFERRED: [Dd][Ee][Ff][Ee][Rr][Rr][Ee][Dd]; DEFINER: [Dd][Ee][Ff][Ii][Nn][Ee][Rr]; DELETE: [Dd][Ee][Ll][Ee][Tt][Ee]; DELIMITER: [Dd][Ee][Ll][Ii][Mm][Ii][Tt][Ee][Rr]; DELIMITERS: [Dd][Ee][Ll][Ii][Mm][Ii][Tt][Ee][Rr][Ss]; DICTIONARY: [Dd][Ii][Cc][Tt][Ii][Oo][Nn][Aa][Rr][Yy]; DISABLE: [Dd][Ii][Ss][Aa][Bb][Ll][Ee]; DISCARD: [Dd][Ii][Ss][Cc][Aa][Rr][Dd]; DOCUMENT: [Dd][Oo][Cc][Uu][Mm][Ee][Nn][Tt]; DOMAIN: [Dd][Oo][Mm][Aa][Ii][Nn]; DOUBLE: [Dd][Oo][Uu][Bb][Ll][Ee]; DROP: [Dd][Rr][Oo][Pp]; EACH: [Ee][Aa][Cc][Hh]; ENABLE: [Ee][Nn][Aa][Bb][Ll][Ee]; ENCODING: [Ee][Nn][Cc][Oo][Dd][Ii][Nn][Gg]; ENCRYPTED: [Ee][Nn][Cc][Rr][Yy][Pp][Tt][Ee][Dd]; ENUM: [Ee][Nn][Uu][Mm]; ESCAPE: [Ee][Ss][Cc][Aa][Pp][Ee]; EVENT: [Ee][Vv][Ee][Nn][Tt]; EXCLUDE: [Ee][Xx][Cc][Ll][Uu][Dd][Ee]; EXCLUDING: [Ee][Xx][Cc][Ll][Uu][Dd][Ii][Nn][Gg]; EXCLUSIVE: [Ee][Xx][Cc][Ll][Uu][Ss][Ii][Vv][Ee]; EXECUTE: [Ee][Xx][Ee][Cc][Uu][Tt][Ee]; EXPLAIN: [Ee][Xx][Pp][Ll][Aa][Ii][Nn]; EXTENSION: [Ee][Xx][Tt][Ee][Nn][Ss][Ii][Oo][Nn]; EXTERNAL: [Ee][Xx][Tt][Ee][Rr][Nn][Aa][Ll]; FAMILY: [Ff][Aa][Mm][Ii][Ll][Yy]; FIRST: [Ff][Ii][Rr][Ss][Tt]; FOLLOWING: [Ff][Oo][Ll][Ll][Oo][Ww][Ii][Nn][Gg]; FORCE: [Ff][Oo][Rr][Cc][Ee]; FORWARD: [Ff][Oo][Rr][Ww][Aa][Rr][Dd]; FUNCTION: [Ff][Uu][Nn][Cc][Tt][Ii][Oo][Nn]; FUNCTIONS: [Ff][Uu][Nn][Cc][Tt][Ii][Oo][Nn][Ss]; GLOBAL: [Gg][Ll][Oo][Bb][Aa][Ll]; GRANTED: [Gg][Rr][Aa][Nn][Tt][Ee][Dd]; HANDLER: [Hh][Aa][Nn][Dd][Ll][Ee][Rr]; HEADER: [Hh][Ee][Aa][Dd][Ee][Rr]; HOLD: [Hh][Oo][Ll][Dd]; HOUR: [Hh][Oo][Uu][Rr]; IDENTITY: [Ii][Dd][Ee][Nn][Tt][Ii][Tt][Yy]; IF: [Ii][Ff]; IMMEDIATE: [Ii][Mm][Mm][Ee][Dd][Ii][Aa][Tt][Ee]; IMMUTABLE: [Ii][Mm][Mm][Uu][Tt][Aa][Bb][Ll][Ee]; IMPLICIT: [Ii][Mm][Pp][Ll][Ii][Cc][Ii][Tt]; INCLUDING: [Ii][Nn][Cc][Ll][Uu][Dd][Ii][Nn][Gg]; INCREMENT: [Ii][Nn][Cc][Rr][Ee][Mm][Ee][Nn][Tt]; INDEX: [Ii][Nn][Dd][Ee][Xx]; INDEXES: [Ii][Nn][Dd][Ee][Xx][Ee][Ss]; INHERIT: [Ii][Nn][Hh][Ee][Rr][Ii][Tt]; INHERITS: [Ii][Nn][Hh][Ee][Rr][Ii][Tt][Ss]; INLINE: [Ii][Nn][Ll][Ii][Nn][Ee]; INPUT: [Ii][Nn][Pp][Uu][Tt]; INSENSITIVE: [Ii][Nn][Ss][Ee][Nn][Ss][Ii][Tt][Ii][Vv][Ee]; INSERT: [Ii][Nn][Ss][Ee][Rr][Tt]; INSTEAD: [Ii][Nn][Ss][Tt][Ee][Aa][Dd]; INVOKER: [Ii][Nn][Vv][Oo][Kk][Ee][Rr]; ISOLATION: [Ii][Ss][Oo][Ll][Aa][Tt][Ii][Oo][Nn]; KEY: [Kk][Ee][Yy]; LABEL: [Ll][Aa][Bb][Ee][Ll]; LANGUAGE: [Ll][Aa][Nn][Gg][Uu][Aa][Gg][Ee]; LARGE: [Ll][Aa][Rr][Gg][Ee]; LAST: [Ll][Aa][Ss][Tt]; LC_COLLATE: [Ll][Cc][_][Cc][Oo][Ll][Ll][Aa][Tt][Ee]; LC_CTYPE: [Ll][Cc][_][Cc][Tt][Yy][Pp][Ee]; LEAKPROOF: [Ll][Ee][Aa][Kk][Pp][Rr][Oo][Oo][Ff]; LEVEL: [Ll][Ee][Vv][Ee][Ll]; LISTEN: [Ll][Ii][Ss][Tt][Ee][Nn]; LOAD: [Ll][Oo][Aa][Dd]; LOCAL: [Ll][Oo][Cc][Aa][Ll]; LOCATION: [Ll][Oo][Cc][Aa][Tt][Ii][Oo][Nn]; LOCK: [Ll][Oo][Cc][Kk]; MAPPING: [Mm][Aa][Pp][Pp][Ii][Nn][Gg]; MATCH: [Mm][Aa][Tt][Cc][Hh]; MATERIALIZED: [Mm][Aa][Tt][Ee][Rr][Ii][Aa][Ll][Ii][Zz][Ee][Dd]; MAXVALUE: [Mm][Aa][Xx][Vv][Aa][Ll][Uu][Ee]; MINUTE: [Mm][Ii][Nn][Uu][Tt][Ee]; MINVALUE: [Mm][Ii][Nn][Vv][Aa][Ll][Uu][Ee]; MODE: [Mm][Oo][Dd][Ee]; MONTH: [Mm][Oo][Nn][Tt][Hh]; MOVE: [Mm][Oo][Vv][Ee]; NAME: [Nn][Aa][Mm][Ee]; NAMES: [Nn][Aa][Mm][Ee][Ss]; NEXT: [Nn][Ee][Xx][Tt]; NO: [Nn][Oo]; NOTHING: [Nn][Oo][Tt][Hh][Ii][Nn][Gg]; NOTIFY: [Nn][Oo][Tt][Ii][Ff][Yy]; NOWAIT: [Nn][Oo][Ww][Aa][Ii][Tt]; NULLS: [Nn][Uu][Ll][Ll][Ss]; OBJECT: [Oo][Bb][Jj][Ee][Cc][Tt]; OF: [Oo][Ff]; OFF: [Oo][Ff][Ff]; OIDS: [Oo][Ii][Dd][Ss]; OPERATOR: [Oo][Pp][Ee][Rr][Aa][Tt][Oo][Rr]; OPTION: [Oo][Pp][Tt][Ii][Oo][Nn]; OPTIONS: [Oo][Pp][Tt][Ii][Oo][Nn][Ss]; OWNED: [Oo][Ww][Nn][Ee][Dd]; OWNER: [Oo][Ww][Nn][Ee][Rr]; PARSER: [Pp][Aa][Rr][Ss][Ee][Rr]; PARTIAL: [Pp][Aa][Rr][Tt][Ii][Aa][Ll]; PARTITION: [Pp][Aa][Rr][Tt][Ii][Tt][Ii][Oo][Nn]; PASSING: [Pp][Aa][Ss][Ss][Ii][Nn][Gg]; PASSWORD: [Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]; PLANS: [Pp][Ll][Aa][Nn][Ss]; PRECEDING: [Pp][Rr][Ee][Cc][Ee][Dd][Ii][Nn][Gg]; PREPARE: [Pp][Rr][Ee][Pp][Aa][Rr][Ee]; PREPARED: [Pp][Rr][Ee][Pp][Aa][Rr][Ee][Dd]; PRESERVE: [Pp][Rr][Ee][Ss][Ee][Rr][Vv][Ee]; PRIOR: [Pp][Rr][Ii][Oo][Rr]; PRIVILEGES: [Pp][Rr][Ii][Vv][Ii][Ll][Ee][Gg][Ee][Ss]; PROCEDURAL: [Pp][Rr][Oo][Cc][Ee][Dd][Uu][Rr][Aa][Ll]; PROCEDURE: [Pp][Rr][Oo][Cc][Ee][Dd][Uu][Rr][Ee]; PROGRAM: [Pp][Rr][Oo][Gg][Rr][Aa][Mm]; QUOTE: [Qq][Uu][Oo][Tt][Ee]; RANGE: [Rr][Aa][Nn][Gg][Ee]; READ: [Rr][Ee][Aa][Dd]; REASSIGN: [Rr][Ee][Aa][Ss][Ss][Ii][Gg][Nn]; RECHECK: [Rr][Ee][Cc][Hh][Ee][Cc][Kk]; RECURSIVE: [Rr][Ee][Cc][Uu][Rr][Ss][Ii][Vv][Ee]; REF: [Rr][Ee][Ff]; REFRESH: [Rr][Ee][Ff][Rr][Ee][Ss][Hh]; REINDEX: [Rr][Ee][Ii][Nn][Dd][Ee][Xx]; RELATIVE: [Rr][Ee][Ll][Aa][Tt][Ii][Vv][Ee]; RELEASE: [Rr][Ee][Ll][Ee][Aa][Ss][Ee]; RENAME: [Rr][Ee][Nn][Aa][Mm][Ee]; REPEATABLE: [Rr][Ee][Pp][Ee][Aa][Tt][Aa][Bb][Ll][Ee]; REPLACE: [Rr][Ee][Pp][Ll][Aa][Cc][Ee]; REPLICA: [Rr][Ee][Pp][Ll][Ii][Cc][Aa]; RESET: [Rr][Ee][Ss][Ee][Tt]; RESTART: [Rr][Ee][Ss][Tt][Aa][Rr][Tt]; RESTRICT: [Rr][Ee][Ss][Tt][Rr][Ii][Cc][Tt]; RETURNS: [Rr][Ee][Tt][Uu][Rr][Nn][Ss]; REVOKE: [Rr][Ee][Vv][Oo][Kk][Ee]; ROLE: [Rr][Oo][Ll][Ee]; ROLLBACK: [Rr][Oo][Ll][Ll][Bb][Aa][Cc][Kk]; ROWS: [Rr][Oo][Ww][Ss]; RULE: [Rr][Uu][Ll][Ee]; SAVEPOINT: [Ss][Aa][Vv][Ee][Pp][Oo][Ii][Nn][Tt]; SCHEMA: [Ss][Cc][Hh][Ee][Mm][Aa]; SCROLL: [Ss][Cc][Rr][Oo][Ll][Ll]; SEARCH: [Ss][Ee][Aa][Rr][Cc][Hh]; SECOND: [Ss][Ee][Cc][Oo][Nn][Dd]; SECURITY: [Ss][Ee][Cc][Uu][Rr][Ii][Tt][Yy]; SEQUENCE: [Ss][Ee][Qq][Uu][Ee][Nn][Cc][Ee]; SEQUENCES: [Ss][Ee][Qq][Uu][Ee][Nn][Cc][Ee][Ss]; SERIALIZABLE: [Ss][Ee][Rr][Ii][Aa][Ll][Ii][Zz][Aa][Bb][Ll][Ee]; SERVER: [Ss][Ee][Rr][Vv][Ee][Rr]; SESSION: [Ss][Ee][Ss][Ss][Ii][Oo][Nn]; SET: [Ss][Ee][Tt]; SHARE: [Ss][Hh][Aa][Rr][Ee]; SHOW: [Ss][Hh][Oo][Ww]; SIMPLE: [Ss][Ii][Mm][Pp][Ll][Ee]; SNAPSHOT: [Ss][Nn][Aa][Pp][Ss][Hh][Oo][Tt]; STABLE: [Ss][Tt][Aa][Bb][Ll][Ee]; STANDALONE: [Ss][Tt][Aa][Nn][Dd][Aa][Ll][Oo][Nn][Ee]; START: [Ss][Tt][Aa][Rr][Tt]; STATEMENT: [Ss][Tt][Aa][Tt][Ee][Mm][Ee][Nn][Tt]; STATISTICS: [Ss][Tt][Aa][Tt][Ii][Ss][Tt][Ii][Cc][Ss]; STDIN: [Ss][Tt][Dd][Ii][Nn]; STDOUT: [Ss][Tt][Dd][Oo][Uu][Tt]; STORAGE: [Ss][Tt][Oo][Rr][Aa][Gg][Ee]; STRICT: [Ss][Tt][Rr][Ii][Cc][Tt]; STRIP: [Ss][Tt][Rr][Ii][Pp]; SYSID: [Ss][Yy][Ss][Ii][Dd]; SYSTEM: [Ss][Yy][Ss][Tt][Ee][Mm]; TABLES: [Tt][Aa][Bb][Ll][Ee][Ss]; TABLESPACE: [Tt][Aa][Bb][Ll][Ee][Ss][Pp][Aa][Cc][Ee]; TEMP: [Tt][Ee][Mm][Pp]; TEMPLATE: [Tt][Ee][Mm][Pp][Ll][Aa][Tt][Ee]; TEMPORARY: [Tt][Ee][Mm][Pp][Oo][Rr][Aa][Rr][Yy]; TEXT: [Tt][Ee][Xx][Tt]; TRANSACTION: [Tt][Rr][Aa][Nn][Ss][Aa][Cc][Tt][Ii][Oo][Nn]; TRIGGER: [Tt][Rr][Ii][Gg][Gg][Ee][Rr]; TRUNCATE: [Tt][Rr][Uu][Nn][Cc][Aa][Tt][Ee]; TRUSTED: [Tt][Rr][Uu][Ss][Tt][Ee][Dd]; TYPE: [Tt][Yy][Pp][Ee]; TYPES: [Tt][Yy][Pp][Ee][Ss]; UNBOUNDED: [Uu][Nn][Bb][Oo][Uu][Nn][Dd][Ee][Dd]; UNCOMMITTED: [Uu][Nn][Cc][Oo][Mm][Mm][Ii][Tt][Tt][Ee][Dd]; UNENCRYPTED: [Uu][Nn][Ee][Nn][Cc][Rr][Yy][Pp][Tt][Ee][Dd]; UNKNOWN: [Uu][Nn][Kk][Nn][Oo][Ww][Nn]; UNLISTEN: [Uu][Nn][Ll][Ii][Ss][Tt][Ee][Nn]; UNLOGGED: [Uu][Nn][Ll][Oo][Gg][Gg][Ee][Dd]; UNTIL: [Uu][Nn][Tt][Ii][Ll]; UPDATE: [Uu][Pp][Dd][Aa][Tt][Ee]; VACUUM: [Vv][Aa][Cc][Uu][Uu][Mm]; VALID: [Vv][Aa][Ll][Ii][Dd]; VALIDATE: [Vv][Aa][Ll][Ii][Dd][Aa][Tt][Ee]; VALIDATOR: [Vv][Aa][Ll][Ii][Dd][Aa][Tt][Oo][Rr]; VALUE: [Vv][Aa][Ll][Uu][Ee]; VARYING: [Vv][Aa][Rr][Yy][Ii][Nn][Gg]; VERSION: [Vv][Ee][Rr][Ss][Ii][Oo][Nn]; VIEW: [Vv][Ii][Ee][Ww]; VOLATILE: [Vv][Oo][Ll][Aa][Tt][Ii][Ll][Ee]; WHITESPACE: [Ww][Hh][Ii][Tt][Ee][Ss][Pp][Aa][Cc][Ee]; WITHOUT: [Ww][Ii][Tt][Hh][Oo][Uu][Tt]; WORK: [Ww][Oo][Rr][Kk]; WRAPPER: [Ww][Rr][Aa][Pp][Pp][Ee][Rr]; WRITE: [Ww][Rr][Ii][Tt][Ee]; XML: [Xx][Mm][Ll]; YEAR: [Yy][Ee][Aa][Rr]; YES: [Yy][Ee][Ss]; ZONE: [Zz][Oo][Nn][Ee]; // // non-reserved keywords (cannot be function or type) // // BETWEEN: [Bb][Ee][Tt][Ww][Ee][Ee][Nn]; BIGINT: [Bb][Ii][Gg][Ii][Nn][Tt]; BIT: [Bb][Ii][Tt]; BOOLEAN: [Bb][Oo][Oo][Ll][Ee][Aa][Nn]; CHAR: [Cc][Hh][Aa][Rr]; CHARACTER: [Cc][Hh][Aa][Rr][Aa][Cc][Tt][Ee][Rr]; COALESCE: [Cc][Oo][Aa][Ll][Ee][Ss][Cc][Ee]; DEC: [Dd][Ee][Cc]; DECIMAL: [Dd][Ee][Cc][Ii][Mm][Aa][Ll]; EXISTS: [Ee][Xx][Ii][Ss][Tt][Ss]; EXTRACT: [Ee][Xx][Tt][Rr][Aa][Cc][Tt]; FLOAT: [Ff][Ll][Oo][Aa][Tt]; GREATEST: [Gg][Rr][Ee][Aa][Tt][Ee][Ss][Tt]; INOUT: [Ii][Nn][Oo][Uu][Tt]; INT: [Ii][Nn][Tt]; INTEGER: [Ii][Nn][Tt][Ee][Gg][Ee][Rr]; INTERVAL: [Ii][Nn][Tt][Ee][Rr][Vv][Aa][Ll]; LEAST: [Ll][Ee][Aa][Ss][Tt]; NATIONAL: [Nn][Aa][Tt][Ii][Oo][Nn][Aa][Ll]; NCHAR: [Nn][Cc][Hh][Aa][Rr]; NONE: [Nn][Oo][Nn][Ee]; NULLIF: [Nn][Uu][Ll][Ll][Ii][Ff]; NUMERIC: [Nn][Uu][Mm][Ee][Rr][Ii][Cc]; OUT: [Oo][Uu][Tt]; OVERLAY: [Oo][Vv][Ee][Rr][Ll][Aa][Yy]; POSITION: [Pp][Oo][Ss][Ii][Tt][Ii][Oo][Nn]; PRECISION: [Pp][Rr][Ee][Cc][Ii][Ss][Ii][Oo][Nn]; REAL: [Rr][Ee][Aa][Ll]; ROW: [Rr][Oo][Ww]; SETOF: [Ss][Ee][Tt][Oo][Ff]; SMALLINT: [Ss][Mm][Aa][Ll][Ll][Ii][Nn][Tt]; SUBSTRING: [Ss][Uu][Bb][Ss][Tt][Rr][Ii][Nn][Gg]; TIME: [Tt][Ii][Mm][Ee]; TIMESTAMP: [Tt][Ii][Mm][Ee][Ss][Tt][Aa][Mm][Pp]; TREAT: [Tt][Rr][Ee][Aa][Tt]; TRIM: [Tt][Rr][Ii][Mm]; VALUES: [Vv][Aa][Ll][Uu][Ee][Ss]; VARCHAR: [Vv][Aa][Rr][Cc][Hh][Aa][Rr]; XMLATTRIBUTES: [Xx][Mm][Ll][Aa][Tt][Tt][Rr][Ii][Bb][Uu][Tt][Ee][Ss]; XMLCONCAT: [Xx][Mm][Ll][Cc][Oo][Nn][Cc][Aa][Tt]; XMLELEMENT: [Xx][Mm][Ll][Ee][Ll][Ee][Mm][Ee][Nn][Tt]; XMLEXISTS: [Xx][Mm][Ll][Ee][Xx][Ii][Ss][Tt][Ss]; XMLFOREST: [Xx][Mm][Ll][Ff][Oo][Rr][Ee][Ss][Tt]; XMLPARSE: [Xx][Mm][Ll][Pp][Aa][Rr][Ss][Ee]; XMLPI: [Xx][Mm][Ll][Pp][Ii]; XMLROOT: [Xx][Mm][Ll][Rr][Oo][Oo][Tt]; XMLSERIALIZE: [Xx][Mm][Ll][Ss][Ee][Rr][Ii][Aa][Ll][Ii][Zz][Ee]; // // IDENTIFIERS (§4.1.1) // // Identifier: IdentifierStartChar IdentifierChar*; fragment IdentifierStartChar: // these are the valid identifier start characters below 0x7F [a-zA-Z_] | // these are the valid characters from 0x80 to 0xFF [\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u00FF] | // these are the letters above 0xFF which only need a single UTF-16 code unit [\\u0100-\\uD7FF\\uE000-\\uFFFF] {Character.isLetter((char)_input.LA(-1))}? | // letters which require multiple UTF-16 code units [\\uD800-\\uDBFF] [\\uDC00-\\uDFFF] {Character.isLetter(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1))) }?; fragment IdentifierChar: StrictIdentifierChar | '$'; fragment StrictIdentifierChar: IdentifierStartChar | [0-9]; /* Quoted Identifiers * * These are divided into four separate tokens, allowing distinction of valid quoted identifiers * from invalid quoted identifiers without sacrificing the ability of the lexer to reliably recover * from lexical errors in the input. */ QuotedIdentifier: UnterminatedQuotedIdentifier '""'; // This is a quoted identifier which only contains valid characters but is not terminated UnterminatedQuotedIdentifier: '""' ( '""""' | ~[\\u0000""])*; // This is a quoted identifier which is terminated but contains a \\u0000 character InvalidQuotedIdentifier: InvalidUnterminatedQuotedIdentifier '""'; // This is a quoted identifier which is unterminated and contains a \\u0000 character InvalidUnterminatedQuotedIdentifier: '""' ( '""""' | ~'""')*; /* Unicode Quoted Identifiers * * These are divided into four separate tokens, allowing distinction of valid Unicode quoted * identifiers from invalid Unicode quoted identifiers without sacrificing the ability of the lexer * to reliably recover from lexical errors in the input. Note that escape sequences are never * checked as part of this determination due to the ability of users to change the escape character * with a UESCAPE clause following the Unicode quoted identifier. * * TODO: these rules assume """" is still a valid escape sequence within a Unicode quoted identifier. */ UnicodeQuotedIdentifier: [Uu] '&' QuotedIdentifier; // This is a Unicode quoted identifier which only contains valid characters but is not terminated UnterminatedUnicodeQuotedIdentifier: [Uu] '&' UnterminatedQuotedIdentifier; // This is a Unicode quoted identifier which is terminated but contains a \\u0000 character InvalidUnicodeQuotedIdentifier: [Uu] '&' InvalidQuotedIdentifier; // This is a Unicode quoted identifier which is unterminated and contains a \\u0000 character InvalidUnterminatedUnicodeQuotedIdentifier: [Uu] '&' InvalidUnterminatedQuotedIdentifier; // // CONSTANTS (§4.1.2) // // // String Constants (§4.1.2.1) StringConstant: UnterminatedStringConstant '\\''; UnterminatedStringConstant: '\\'' ( '\\'\\'' | ~'\\'')*; // String Constants with C-style Escapes (§4.1.2.2) BeginEscapeStringConstant: [Ee] '\\'' -> more, pushMode(EscapeStringConstantMode); // String Constants with Unicode Escapes (§4.1.2.3) // // Note that escape sequences are never checked as part of this token due to the ability of users to // change the escape character with a UESCAPE clause following the Unicode string constant. // // TODO: these rules assume '' is still a valid escape sequence within a Unicode string constant. UnicodeEscapeStringConstant: UnterminatedUnicodeEscapeStringConstant '\\''; UnterminatedUnicodeEscapeStringConstant: [Uu] '&' UnterminatedStringConstant; // Dollar-quoted String Constants (§4.1.2.4) BeginDollarStringConstant: '$' Tag? '$' {_tags.push(getText());} -> pushMode(DollarQuotedStringMode); /* ""The tag, if any, of a dollar-quoted string follows the same rules as an unquoted identifier, * except that it cannot contain a dollar sign."" */ fragment Tag: IdentifierStartChar StrictIdentifierChar*; // Bit-strings Constants (§4.1.2.5) BinaryStringConstant: UnterminatedBinaryStringConstant '\\''; UnterminatedBinaryStringConstant: [Bb] '\\'' [01]*; InvalidBinaryStringConstant: InvalidUnterminatedBinaryStringConstant '\\''; InvalidUnterminatedBinaryStringConstant: [Bb] UnterminatedStringConstant; HexadecimalStringConstant: UnterminatedHexadecimalStringConstant '\\''; UnterminatedHexadecimalStringConstant: [Xx] '\\'' [0-9a-fA-F]*; InvalidHexadecimalStringConstant: InvalidUnterminatedHexadecimalStringConstant '\\''; InvalidUnterminatedHexadecimalStringConstant: [Xx] UnterminatedStringConstant; // Numeric Constants (§4.1.2.6) Integral: Digits; Numeric: Digits '.' Digits? ([Ee] [+-]? Digits)? | '.' Digits ([Ee] [+-]? Digits)? | Digits [Ee] [+-]? Digits; fragment Digits: [0-9]+; // // WHITESPACE (§4.1?) // // Whitespace: [ \\t]+ -> channel(HIDDEN); Newline: ( '\\r' '\\n'? | '\\n') -> channel(HIDDEN); // // COMMENTS (§4.1.5) // // LineComment: '--' ~[\\r\\n]* -> channel(HIDDEN); BlockComment: ( '/*' ( '/'* BlockComment | ~[/*] | '/'+ ~[/*] | '*'+ ~[/*] )* '*'* '*/' ) -> channel(HIDDEN); UnterminatedBlockComment: '/*' ( '/'* BlockComment | // these characters are not part of special sequences in a block comment ~[/*] | // handle / or * characters which are not part of /* or */ and do not appear at the end of the file ('/'+ ~[/*] | '*'+ ~[/*]) )* // Handle the case of / or * characters at the end of the file, or a nested unterminated block comment ('/'+ | '*'+ | '/'* UnterminatedBlockComment)? // Optional assertion to make sure this rule is working as intended {assert _input.LA(1) == EOF;}; // // META-COMMANDS // // // http://www.postgresql.org/docs/9.3/static/app-psql.html MetaCommand: '\\\\' (~[\\r\\n\\\\""] | '""' ~[\\r\\n""]* '""')* ('""' ~[\\r\\n""]*)?; EndMetaCommand: '\\\\\\\\'; // // ERROR // // // Any character which does not match one of the above rules will appear in the token stream as an // ErrorCharacter token. This ensures the lexer itself will never encounter a syntax error, so all // error handling may be performed by the parser. ErrorCharacter: .; mode EscapeStringConstantMode; EscapeStringConstant: EscapeStringText '\\'' -> mode(AfterEscapeStringConstantMode); UnterminatedEscapeStringConstant: EscapeStringText // Handle a final unmatched \\ character appearing at the end of the file '\\\\'? EOF; fragment EscapeStringText: ( '\\'\\'' | '\\\\' ( // two-digit hex escapes are still valid when treated as single-digit escapes 'x' [0-9a-fA-F] | 'u' [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] | 'U' [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] | // Any character other than the Unicode escapes can follow a backslash. Some have special meaning, // but that doesn't affect the syntax. ~[xuU] ) | ~['\\\\] )*; InvalidEscapeStringConstant: InvalidEscapeStringText '\\'' -> mode(AfterEscapeStringConstantMode); InvalidUnterminatedEscapeStringConstant: InvalidEscapeStringText // Handle a final unmatched \\ character appearing at the end of the file '\\\\'? EOF; fragment InvalidEscapeStringText: ( '\\'\\'' | '\\\\' . | ~['\\\\])*; mode AfterEscapeStringConstantMode; AfterEscapeStringConstantMode_Whitespace: Whitespace -> type(Whitespace), channel(HIDDEN); AfterEscapeStringConstantMode_Newline: Newline -> type(Newline), channel(HIDDEN), mode(AfterEscapeStringConstantWithNewlineMode); AfterEscapeStringConstantMode_NotContinued: {} // intentionally empty -> skip, popMode; mode AfterEscapeStringConstantWithNewlineMode; AfterEscapeStringConstantWithNewlineMode_Whitespace: Whitespace -> type(Whitespace), channel(HIDDEN); AfterEscapeStringConstantWithNewlineMode_Newline: Newline -> type(Newline), channel(HIDDEN); AfterEscapeStringConstantWithNewlineMode_Continued: '\\'' -> more, mode(EscapeStringConstantMode); AfterEscapeStringConstantWithNewlineMode_NotContinued: {} // intentionally empty -> skip, popMode; mode DollarQuotedStringMode; Text: ~'$'+ | // this alternative improves the efficiency of handling $ characters within a dollar-quoted string which are // not part of the ending tag. '$' ~'$'*; EndDollarStringConstant: '$' Tag? '$' {getText().equals(_tags.peek())}? {_tags.pop();} -> popMode;",12519,True,2847.297119488786,median " JavaScript Tutorial
    THE WORLD'S LARGEST WEB DEVELOPER SITE
    ×

    JS Tutorial

    JS HOME JS Introduction JS Where To JS Output JS Syntax JS Statements JS Comments JS Variables JS Operators JS Arithmetic JS Assignment JS Data Types JS Functions JS Objects JS Scope JS Events JS Strings JS String Methods JS Numbers JS Number Methods JS Math JS Random JS Dates JS Date Formats JS Date Methods JS Arrays JS Array Methods JS Array Sort JS Booleans JS Comparisons JS Conditions JS Switch JS Loop For JS Loop While JS Break JS Type Conversion JS Bitwise JS RegExp JS Errors JS Debugging JS Hoisting JS Strict Mode JS Style Guide JS Best Practices JS Mistakes JS Performance JS Reserved Words JS Versions JS JSON

    JS Forms

    JS Forms Forms API

    JS Objects

    Object Definitions Object Properties Object Methods Object Prototypes

    JS Functions

    Function Definitions Function Parameters Function Invocation Function Call Function Apply Function Closures

    JS HTML DOM

    DOM Intro DOM Methods DOM Document DOM Elements DOM HTML DOM CSS DOM Animations DOM Events DOM Event Listener DOM Navigation DOM Nodes DOM Collections DOM Node Lists

    JS Browser BOM

    JS Window JS Screen JS Location JS History JS Navigator JS Popup Alert JS Timing JS Cookies

    JS AJAX

    AJAX Intro AJAX XMLHttp AJAX Request AJAX Response AJAX XML File AJAX PHP AJAX ASP AJAX Database AJAX Applications AJAX Examples

    JS JSON

    JSON Intro JSON Syntax JSON vs XML JSON Data Types JSON Objects JSON Arrays JSON Parse JSON Stringify JSON PHP JSON HTML JSON JSONP

    JS Examples

    JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Quiz JS Certificate

    JS References

    JavaScript Objects HTML DOM Objects


    JavaScript Tutorial

    JavaScript is the programming language of HTML and the Web.

    JavaScript is easy to learn.

    This tutorial will teach you JavaScript from basic to advanced.


    Examples in Each Chapter

    With our "Try it Yourself" editor, you can change all examples and view the results.

    Example

    My First JavaScript

    Try it Yourself »

    We recommend reading this tutorial, in the sequence listed in the left menu.


    Learn by Examples

    Examples are better than 1000 words. Examples are often easier to understand than text explanations.

    This tutorial supplements all explanations with clarifying "Try it Yourself" examples.

    JavaScript Examples

    If you try all the examples, you will learn a lot about JavaScript, in a very short time!


    Why Study JavaScript?

    JavaScript is one of the 3 languages all web developers must learn:

       1. HTML to define the content of web pages

       2. CSS to specify the layout of web pages

       3. JavaScript to program the behavior of web pages

    This tutorial is about JavaScript, and how JavaScript works with HTML and CSS.

    Did You Know?

    JavaScript and Java are completely different languages, both in concept and design.

    JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
    ECMA-262 is the official name of the standard. ECMAScript is the official name of the language.

    You can read more about the different JavaScript versions in the chapter JS Versions.



    Learning Speed

    In this tutorial, the learning speed is your choice.

    Everything is up to you.

    If you are struggling, take a break, or reread the material.

    Always make sure you understand all the "Try-it-Yourself" examples.


    JavaScript References

    W3Schools maintains a complete JavaScript reference, including all HTML and browser objects.

    The reference contains examples for all properties and methods, and is continuously updated according to the latest web standards.

    Complete JavaScript Reference


    JavaScript Quiz Test

    Test your JavaScript skills at W3Schools!

    Start JavaScript Quiz!


    JavaScript Exam - Get Your Diploma!

    W3Schools' Online Certification

    The perfect solution for professionals who need to balance work, family, and career building.

    More than 10 000 certificates already issued!

    Get Your Certificate »

    The HTML Certificate documents your knowledge of HTML.

    The CSS Certificate documents your knowledge of advanced CSS.

    The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.

    The jQuery Certificate documents your knowledge of jQuery.

    The PHP Certificate documents your knowledge of PHP and SQL (MySQL).

    The XML Certificate documents your knowledge of XML, XML DOM and XSLT.

    The Bootstrap Certificate documents your knowledge of the Bootstrap framework.


    SHARE



    CERTIFICATES

    HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML.

    Read More »



    ×

    Your Suggestion:


    ×

    Thank You For Helping Us!

    Your message has been sent to W3Schools.


    W3Schools is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2017 by Refsnes Data. All Rights Reserved.
    Powered by W3.CSS.



    ",16265,False,2424.4036842415403,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, ANSI SQL parsing mode is enabled. */ public boolean ansi = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; singleInterval : INTERVAL? multiUnitsInterval EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER database db=errorCapturingIdentifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | ALTER database db=errorCapturingIdentifier SET locationSpec #setDatabaseLocation | DROP (database | NAMESPACE) (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE multipartIdentifier RENAME COLUMN from=qualifiedName TO to=identifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=qualifiedNameList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=qualifiedNameList #dropTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE multipartIdentifier (ALTER | CHANGE) COLUMN? qualifiedName (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE tableIdentifier partitionSpec? CHANGE COLUMN? colName=errorCapturingIdentifier colType colPosition? #changeColumn | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER TABLE tableIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER VIEW tableIdentifier ADD (IF NOT EXISTS)? partitionSpec+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW tableIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? qualifiedName AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? qualifiedName #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=errorCapturingIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) namespace=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (qualifiedName | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) database EXTENDED? db=errorCapturingIdentifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING qualifiedName ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assign (',' assign)* ; assign : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? | {ansi}? (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval) ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER qualifiedName ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=qualifiedName dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!ansi}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {ansi}? ansiNonReserved #unquotedIdentifier | {!ansi}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `spark.sql.ansi.enabled=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `spark.sql.ansi.enabled=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `spark.sql.ansi.enabled=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12131,False,2272.2815611326782,median "<%@ Control Language=""C#"" AutoEventWireup=""true"" CodeBehind=""NewNormalLoan.ascx.cs"" Inherits=""BankProject.Views.TellerApplication.NewNormalLoan"" %> <%@ Register Assembly=""Telerik.Web.UI"" Namespace=""Telerik.Web.UI"" TagPrefix=""telerik"" %> <%@ Register Assembly=""DotNetNuke.web"" Namespace=""DotNetNuke.Web.UI.WebControls"" TagPrefix=""dnn"" %> <%@ Register Src=""~/controls/LabelControl.ascx"" TagPrefix=""dnn"" TagName=""Label"" %>
    Contract Details <%----%> <%--
    Main Category:(*)
    Sub Category:(*)
    Purpose Code:(*)
    Customer ID:(*) <%# DataBinder.Eval(Container.DataItem,""CustomerID"") %> - <%# DataBinder.Eval(Container.DataItem,""GBFullName"") %>
    Customer ID:(*)
    -
    Loan Group:
    --%>
    Currency: Business Day: <%# DataBinder.Eval(Container.DataItem,""MaQuocGia"") %> - <%# DataBinder.Eval(Container.DataItem,""TenTA"") %>
    Loan Amount:(*) Approved Amt:
    Open Date:(*) Drawdown Date:
    Value Date: Maturity Date:(*)
    Credit to Account:
    Limit Reference:(*)
    INTEREST Details
    Rate Type: <%--Du no giam dan--%> <%--Du no ban dau--%> <%--Du no giam dan, truot lai xuat + Ins speed--%>
    Interest Basis: 366/360
    Int Pay Method: Interest Rate:(*)
    Deposit Rate: Int Spread:
    Define Schedule (Y/N): Loan Status:
    Total Interest Amt: Past Due Amount:
    Charge Code
    Charge Amount
    Charge Date
    Repayment Details
    Prin Rep Account
    Int Rep Account
    Chrg Rep Account
    Credit Scoring Details
    Credit scoring
    Credit rating
    Other Details
    Customer Remarks (*) <%-- --%>
    Account Officer(*)
    Secured (Y/N)(*)
    Collateral ID <%-- --%>
    <%-- --%>
    <%-- --%>
    <%-- --%>
    Collateral Amount <%-- --%>
    Country Risk
    Legacy.Ref

     

    Forward/Backward Key (*) FWD IN MONTH Base Date Key (*) Base Date

    I P I+P AC EP M 2M 3M 4M 5M 6M 7M 8M 9M 10M 11M 12M E    
    No data was returned.
    I P I+P AC EP <%--cho phép user định nghĩa số tiền cần phải trả trong Kỳ Cuối--%> M 2M 3M 4M 5M 6M 7M 8M 9M 10M 11M 12M <%--12M: Định kỳ trả 12 tháng--%> E <%--E: Thanh toán Cuối kỳ--%>    
       
       
    Type (*) Date Amount - Diary Action Rate Chrg No Frequency
    <%----%>

     

           
    No data was returned.
           
    Disbursal Date Disbursal Amount Drawdown Date
    ",16307,True,2965.9705217789397,median "<%@ Page Language=""C#"" AutoEventWireup=""true"" CodeFile=""TestForm.aspx.cs"" Inherits=""TestForm"" %> RentHere - Homepage
    My cart

    2 item(s) - $1,262.00

    Product

    Jewelry & Watches ▼
    • Jewelry & Watches
    • Electronics
    • Sports & Outdoors
    New Quickview

    "" SelectCommand=""SELECT [img1], [name], [pricePerDay] FROM [Item]"">
    • FACEBOOK
    • TWITTER FEEDS
    • YouTube
    ",16303,True,3246.556106245287,median "lexer grammar TSQLLexer; @header {package cz.startnet.utils.pgdiff.parsers.antlr;} // Basic keywords (from https://msdn.microsoft.com/en-us/library/ms189822.aspx) ADD: A D D; // first identifier rule, sync with CustomTSQLAntlrErrorStrategy ALL: A L L; ALTER: A L T E R; AND: A N D; ANY: A N Y; AS: A S; ASC: A S C; AUTHORIZATION: A U T H O R I Z A T I O N; BACKUP: B A C K U P; BEGIN: B E G I N; BETWEEN: B E T W E E N; BREAK: B R E A K; BROWSE: B R O W S E; BULK: B U L K; BY: B Y; CASCADE: C A S C A D E; CASE: C A S E; CHECK: C H E C K; CHECKPOINT: C H E C K P O I N T; CLOSE: C L O S E; CLUSTERED: C L U S T E R E D; COALESCE: C O A L E S C E; COLLATE: C O L L A T E; COLUMN: C O L U M N; COMMIT: C O M M I T; COMPUTE: C O M P U T E; CONSTRAINT: C O N S T R A I N T; CONTAINS: C O N T A I N S; CONTAINSTABLE: C O N T A I N S T A B L E; CONTINUE: C O N T I N U E; CONVERT: (T R Y '_')? C O N V E R T; CREATE: C R E A T E; CROSS: C R O S S; CURRENT: C U R R E N T; CURRENT_DATE: C U R R E N T '_' D A T E; CURRENT_TIME: C U R R E N T '_' T I M E; CURRENT_TIMESTAMP: C U R R E N T '_' T I M E S T A M P; CURRENT_USER: C U R R E N T '_' U S E R; CURSOR: C U R S O R; DATABASE: D A T A B A S E; DBCC: D B C C; DEALLOCATE: D E A L L O C A T E; DECLARE: D E C L A R E; DEFAULT: D E F A U L T; DELETE: D E L E T E; DENY: D E N Y; DESC: D E S C; DISK: D I S K; DISTINCT: D I S T I N C T; DISTRIBUTED: D I S T R I B U T E D; DOUBLE: D O U B L E; DROP: D R O P; DUMP: D U M P; ELSE: E L S E; END: E N D; ERRLVL: E R R L V L; ESCAPE: E S C A P E; EXCEPT: E X C E P T; EXECUTE: E X E C (U T E)?; EXISTS: E X I S T S; EXIT: E X I T; EXTERNAL: E X T E R N A L; FETCH: F E T C H; FILE: F I L E; FILLFACTOR: F I L L F A C T O R; FOR: F O R; FOREIGN: F O R E I G N; FREETEXT: F R E E T E X T; FREETEXTTABLE: F R E E T E X T T A B L E; FROM: F R O M; FULL: F U L L; FUNCTION: F U N C T I O N; GO: G O; GOTO: G O T O; GRANT: G R A N T; GROUP: G R O U P; HAVING: H A V I N G; IDENTITY: I D E N T I T Y; IDENTITY_INSERT: I D E N T I T Y '_' I N S E R T; IDENTITYCOL: I D E N T I T Y C O L; IF: I F; IN: I N; INDEX: I N D E X; INNER: I N N E R; INSERT: I N S E R T; INTERSECT: I N T E R S E C T; INTO: I N T O; IS: I S; JOIN: J O I N; KEY: K E Y; KILL: K I L L; LEFT: L E F T; LIKE: L I K E; LINENO: L I N E N O; LOAD: L O A D; MERGE: M E R G E; NATIONAL: N A T I O N A L; NOCHECK: N O C H E C K; NONCLUSTERED: N O N C L U S T E R E D; NOT: N O T; NULL: N U L L; NULLIF: N U L L I F; OF: O F; OFF: O F F; OFFSETS: O F F S E T S; ON: O N; OPEN: O P E N; OPENDATASOURCE: O P E N D A T A S O U R C E; OPENQUERY: O P E N Q U E R Y; OPENROWSET: O P E N R O W S E T; OPENXML: O P E N X M L; OPTION: O P T I O N; OR: O R; ORDER: O R D E R; OUTER: O U T E R; OVER: O V E R; PERCENT: P E R C E N T; PIVOT: P I V O T; PLAN: P L A N; PRECISION: P R E C I S I O N; PRIMARY: P R I M A R Y; PRINT: P R I N T; PROC: P R O C; PROCEDURE: P R O C E D U R E; PUBLIC: P U B L I C; PYTHON: P Y T H O N; RAISERROR: R A I S E R R O R; READ: R E A D; READTEXT: R E A D T E X T; RECONFIGURE: R E C O N F I G U R E; REFERENCES: R E F E R E N C E S; REPLICATION: R E P L I C A T I O N; RESTORE: R E S T O R E; RESTRICT: R E S T R I C T; RETURN: R E T U R N; REVERT: R E V E R T; REVOKE: R E V O K E; RIGHT: R I G H T; ROLLBACK: R O L L B A C K; ROWCOUNT: R O W C O U N T; ROWGUIDCOL: R O W G U I D C O L; RULE: R U L E; SAVE: S A V E; SCHEMA: S C H E M A; SECURITYAUDIT: S E C U R I T Y A U D I T; SELECT: S E L E C T; SEMANTICKEYPHRASETABLE: S E M A N T I C K E Y P H R A S E T A B L E; SEMANTICSIMILARITYDETAILSTABLE: S E M A N T I C S I M I L A R I T Y D E T A I L S T A B L E; SEMANTICSIMILARITYTABLE: S E M A N T I C S I M I L A R I T Y T A B L E; SESSION_USER: S E S S I O N '_' U S E R; SET: S E T; SETUSER: S E T U S E R; SHUTDOWN: S H U T D O W N; SOME: S O M E; STATISTICS: S T A T I S T I C S; SYSTEM_USER: S Y S T E M '_' U S E R; TABLE: T A B L E; TABLESAMPLE: T A B L E S A M P L E; TEXTSIZE: T E X T S I Z E; THEN: T H E N; TO: T O; TOP: T O P; TRAN: T R A N; TRANSACTION: T R A N S A C T I O N; TRIGGER: T R I G G E R; TRUNCATE: T R U N C A T E; TSEQUAL: T S E Q U A L; UNION: U N I O N; UNIQUE: U N I Q U E; UNPIVOT: U N P I V O T; UPDATE: U P D A T E; UPDATETEXT: U P D A T E T E X T; USE: U S E; USER: U S E R; VALUES: V A L U E S; VARYING: V A R Y I N G; VIEW: V I E W; WAITFOR: W A I T F O R; WHEN: W H E N; WHERE: W H E R E; WHILE: W H I L E; WITH: W I T H; WITHIN_GROUP: W I T H I N ' ' G R O U P; WRITETEXT: W R I T E T E X T; // Reserved system functions FUNC_IDENTITY: '@' '@' I D E N T I T Y; FUNC_CURSOR_ROWS: '@' '@' C U R S O R '_' R O W S; FUNC_DATEFIRST: '@' '@' D A T E F I R S T; FUNC_ERROR: '@' '@' E R R O R; FUNC_FETCH_STATUS: '@' '@' F E T C H '_' S T A T U S; FUNC_PACK_RECEIVED: '@' '@' P A C K '_' R E C E I V E D; FUNC_PROCID: '@' '@' P R O C I D; FUNC_ROWCOUNT: '@' '@' R O W C O U N T; FUNC_TRANCOUNT: '@' '@' T R A N C O U N T; // Additional keywords. They can be id, please keep them in sync with the parser. ABORT_AFTER_WAIT: A B O R T '_' A F T E R '_' W A I T; ABSENT: A B S E N T; ABSOLUTE: A B S O L U T E; ACCENT_SENSITIVITY: A C C E N T '_' S E N S I T I V I T Y; ACTION: A C T I O N; ACTIVATION: A C T I V A T I O N; ACTIVE: A C T I V E; ADDRESS: A D D R E S S; AES_128: A E S '_' '1' '2' '8'; AES_192: A E S '_' '1' '9' '2'; AES_256: A E S '_' '2' '5' '6'; AES: A E S; AFFINITY: A F F I N I T Y; AFTER: A F T E R; AGGREGATE: A G G R E G A T E; ALGORITHM: A L G O R I T H M; ALLOW_CONNECTIONS: A L L O W '_' C O N N E C T I O N S; ALLOW_ENCRYPTED_VALUE_MODIFICATIONS: A L L O W '_' E N C R Y P T E D '_' V A L U E '_' M O D I F I C A T I O N S; ALLOW_MULTIPLE_EVENT_LOSS: A L L O W '_' M U L T I P L E '_' E V E N T '_' L O S S; ALLOW_SINGLE_EVENT_LOSS: A L L O W '_' S I N G L E '_' E V E N T '_' L O S S; ALLOW_SNAPSHOT_ISOLATION: A L L O W '_' S N A P S H O T '_' I S O L A T I O N; ALLOWED: A L L O W E D; ANONYMOUS: A N O N Y M O U S; ANSI_NULL_DEFAULT: A N S I '_' N U L L '_' D E F A U L T; ANSI_NULLS: A N S I '_' N U L L S; ANSI_PADDING: A N S I '_' P A D D I N G; ANSI_WARNINGS: A N S I '_' W A R N I N G S; APPEND: A P P E N D; APPLICATION_LOG: A P P L I C A T I O N '_' L O G; APPLICATION: A P P L I C A T I O N; APPLY: A P P L Y; ARITHABORT: A R I T H A B O R T; ASSEMBLY: A S S E M B L Y; ASYMMETRIC: A S Y M M E T R I C; ASYNCHRONOUS_COMMIT: A S Y N C H R O N O U S '_' C O M M I T; AUDIT_GUID: A U D I T '_' G U I D; AUDIT: A U D I T; AUTHENTICATION: A U T H E N T I C A T I O N; AUTO_CLEANUP: A U T O '_' C L E A N U P; AUTO_CLOSE: A U T O '_' C L O S E; AUTO_CREATE_STATISTICS: A U T O '_' C R E A T E '_' S T A T I S T I C S; AUTO_SHRINK: A U T O '_' S H R I N K; AUTO_UPDATE_STATISTICS_ASYNC: A U T O '_' U P D A T E '_' S T A T I S T I C S '_' A S Y N C; AUTO_UPDATE_STATISTICS: A U T O '_' U P D A T E '_' S T A T I S T I C S; AUTO: A U T O; AUTOGROW_ALL_FILES: A U T O G R O W '_' A L L '_' F I L E S; AUTOGROW_SINGLE_FILE: A U T O G R O W '_' S I N G L E '_' F I L E; AUTOMATED_BACKUP_PREFERENCE: A U T O M A T E D '_' B A C K U P '_' P R E F E R E N C E; AUTOMATIC: A U T O M A T I C; AVAILABILITY_MODE: A V A I L A B I L I T Y '_' M O D E; AVAILABILITY: A V A I L A B I L I T Y; BACKUP_PRIORITY: B A C K U P '_' P R I O R I T Y; BEFORE: B E F O R E; BEGIN_DIALOG: B E G I N '_' D I A L O G; BINARY_BASE64: B I N A R Y ' ' B A S E '6' '4'; BINDING: B I N D I N G; BLOB_STORAGE: B L O B '_' S T O R A G E; BLOCK: B L O C K; BLOCKERS: B L O C K E R S; BLOCKING_HIERARCHY: B L O C K I N G '_' H I E R A R C H Y; BLOCKSIZE: B L O C K S I Z E; BROKER_INSTANCE: B R O K E R '_' I N S T A N C E; BROKER: B R O K E R; BUFFER: B U F F E R; BUFFERCOUNT: B U F F E R C O U N T; BULK_LOGGED: B U L K '_' L O G G E D; CACHE: C A C H E; CALLED: C A L L E D; CALLER: C A L L E R; CAP_CPU_PERCENT: C A P '_' C P U '_' P E R C E N T; CAST: (T R Y '_') ? C A S T; CATALOG: C A T A L O G; CATCH: C A T C H; CERTIFICATE: C E R T I F I C A T E; CHANGE_RETENTION: C H A N G E '_' R E T E N T I O N; CHANGE_TRACKING: C H A N G E '_' T R A C K I N G; CHANGES: C H A N G E S; CHANGETABLE: C H A N G E T A B L E; CHAR: C H A R; CHARACTER: C H A R A C T E R; CHECK_EXPIRATION: C H E C K '_' E X P I R A T I O N; CHECK_POLICY: C H E C K '_' P O L I C Y; CHECKSUM: C H E C K S U M; CLASSIFIER_FUNCTION: C L A S S I F I E R '_' F U N C T I O N; CLEANUP: C L E A N U P; CLUSTER: C L U S T E R; COLLECTION: C O L L E C T I O N; COLUMN_MASTER_KEY: C O L U M N '_' M A S T E R '_' K E Y; COMMITTED: C O M M I T T E D; COMPATIBILITY_LEVEL: C O M P A T I B I L I T Y '_' L E V E L; COMPRESSION: C O M P R E S S I O N; CONCAT_NULL_YIELDS_NULL: C O N C A T '_' N U L L '_' Y I E L D S '_' N U L L; CONCAT: C O N C A T; CONFIGURATION: C O N F I G U R A T I O N; CONNECT: C O N N E C T; CONTAINMENT: C O N T A I N M E N T; CONTENT: C O N T E N T; CONTEXT: C O N T E X T; CONTINUE_AFTER_ERROR: C O N T I N U E '_' A F T E R '_' E R R O R; CONTRACT_NAME: C O N T R A C T '_' N A M E; CONTRACT: C O N T R A C T; CONTROL: C O N T R O L; CONVERSATION: C O N V E R S A T I O N; COOKIE: C O O K I E; COPY_ONLY: C O P Y '_' O N L Y; COUNTER: C O U N T E R; CPU: C P U; CREATE_NEW: C R E A T E '_' N E W; CREATION_DISPOSITION: C R E A T I O N '_' D I S P O S I T I O N; CREDENTIAL: C R E D E N T I A L; CRYPTOGRAPHIC: C R Y P T O G R A P H I C; CURSOR_CLOSE_ON_COMMIT: C U R S O R '_' C L O S E '_' O N '_' C O M M I T; CURSOR_DEFAULT: C U R S O R '_' D E F A U L T; CYCLE: C Y C L E; DATA_COMPRESSION: D A T A '_' C O M P R E S S I O N; DATA_SOURCE: D A T A '_' S O U R C E; DATA: D A T A; DATABASE_MIRRORING: D A T A B A S E '_' M I R R O R I N G; DATE_CORRELATION_OPTIMIZATION: D A T E '_' C O R R E L A T I O N '_' O P T I M I Z A T I O N; DAYS: D A Y S; DB_CHAINING: D B '_' C H A I N I N G; DB_FAILOVER: D B '_' F A I L O V E R; DECRYPTION: D E C R Y P T I O N; DEFAULT_DATABASE: D E F A U L T '_' D A T A B A S E; DEFAULT_FULLTEXT_LANGUAGE: D E F A U L T '_' F U L L T E X T '_' L A N G U A G E; DEFAULT_LANGUAGE: D E F A U L T '_' L A N G U A G E; DEFAULT_SCHEMA: D E F A U L T '_' S C H E M A; DELAY: D E L A Y; DELAYED_DURABILITY: D E L A Y E D '_' D U R A B I L I T Y; DEPENDENTS: D E P E N D E N T S; DES: D E S; DESCRIPTION: D E S C R I P T I O N; DESX: D E S X; DHCP: D H C P; DIAGNOSTICS: D I A G N O S T I C S; DIALOG: D I A L O G; DIFFERENTIAL: D I F F E R E N T I A L; DIRECTORY_NAME: D I R E C T O R Y '_' N A M E; DISABLE_BROKER: D I S A B L E '_' B R O K E R; DISABLE: D I S A B L E; DISABLED: D I S A B L E D; DOCUMENT: D O C U M E N T; DTC_SUPPORT: D T C '_' S U P P O R T; DYNAMIC: D Y N A M I C; ELEMENTS: E L E M E N T S; EMERGENCY: E M E R G E N C Y; EMPTY: E M P T Y; ENABLE_BROKER: E N A B L E '_' B R O K E R; ENABLE: E N A B L E; ENABLED: E N A B L E D; ENCRYPTED_VALUE: E N C R Y P T E D '_' V A L U E; ENCRYPTION: E N C R Y P T I O N; ENDPOINT_URL: E N D P O I N T '_' U R L; ENDPOINT: E N D P O I N T; ERROR_BROKER_CONVERSATIONS: E R R O R '_' B R O K E R '_' C O N V E R S A T I O N S; ERROR: E R R O R; EVENT_RETENTION_MODE: E V E N T '_' R E T E N T I O N '_' M O D E; EVENT: E V E N T; EXCLUSIVE: E X C L U S I V E; EXECUTABLE_FILE: E X E C U T A B L E '_' F I L E; EXECUTABLE: E X E C U T A B L E; EXPAND: E X P A N D; EXPIREDATE: E X P I R E D A T E; EXPIRY_DATE: E X P I R Y '_' D A T E; EXPLICIT: E X P L I C I T; EXTENSION: E X T E N S I O N; EXTERNAL_ACCESS: E X T E R N A L '_' A C C E S S; FAIL_OPERATION: F A I L '_' O P E R A T I O N; FAILOVER_MODE: F A I L O V E R '_' M O D E; FAILOVER: F A I L O V E R; FAILURE_CONDITION_LEVEL: F A I L U R E '_' C O N D I T I O N '_' L E V E L; FAILURECONDITIONLEVEL: F A I L U R E C O N D I T I O N L E V E L; FALSE: F A L S E; FAN_IN: F A N '_' I N; FAST_FORWARD: F A S T '_' F O R W A R D; FAST: F A S T; FILE_SNAPSHOT: F I L E '_' S N A P S H O T; FILEGROUP: F I L E G R O U P; FILEGROWTH: F I L E G R O W T H; FILENAME: F I L E N A M E; FILEPATH: F I L E P A T H; FILESTREAM_ON: F I L E S T R E A M '_' O N; FILESTREAM: F I L E S T R E A M; FILTER: F I L T E R; FIRST: F I R S T; FOLLOWING: F O L L O W I N G; FORCE_FAILOVER_ALLOW_DATA_LOSS: F O R C E '_' F A I L O V E R '_' A L L O W '_' D A T A '_' L O S S; FORCE_SERVICE_ALLOW_DATA_LOSS: F O R C E '_' S E R V I C E '_' A L L O W '_' D A T A '_' L O S S; FORCE: F O R C E; FORCED: F O R C E D; FORCESEEK: F O R C E S E E K; FORMAT: F O R M A T; FORWARD_ONLY: F O R W A R D '_' O N L Y; FULLSCAN: F U L L S C A N; FULLTEXT: F U L L T E X T; GB: G B; GET: G E T; GLOBAL: G L O B A L; GOVERNOR: G O V E R N O R; GROUP_MAX_REQUESTS: G R O U P '_' M A X '_' R E Q U E S T S; HADR: H A D R; HASH: H A S H; HASHED: H A S H E D; HEALTH_CHECK_TIMEOUT: H E A L T H '_' C H E C K '_' T I M E O U T; HEALTHCHECKTIMEOUT: H E A L T H C H E C K T I M E O U T; HIGH: H I G H; HONOR_BROKER_PRIORITY: H O N O R '_' B R O K E R '_' P R I O R I T Y; HOURS: H O U R S; IDENTITY_VALUE: I D E N T I T Y '_' V A L U E; IIF: I I F; IGNORE_NONCLUSTERED_COLUMNSTORE_INDEX: I G N O R E '_' N O N C L U S T E R E D '_' C O L U M N S T O R E '_' I N D E X; IMMEDIATE: I M M E D I A T E; IMPERSONATE: I M P E R S O N A T E; IMPORTANCE: I M P O R T A N C E; INCLUDE_NULL_VALUES: I N C L U D E '_' N U L L '_' V A L U E S; INCLUDE: I N C L U D E; INCREMENT: I N C R E M E N T; INCREMENTAL: I N C R E M E N T A L; INFINITE: I N F I N I T E; INIT: I N I T; INITIATOR: I N I T I A T O R; INPUT: I N P U T; INSENSITIVE: I N S E N S I T I V E; INSTEAD: I N S T E A D; IO: I O; IP: I P; ISOLATION: I S O L A T I O N; JSON: J S O N; KB: K B; KEEP: K E E P; KEEPFIXED: K E E P F I X E D; KERBEROS: K E R B E R O S; KEY_PATH: K E Y '_' P A T H; KEY_SOURCE: K E Y '_' S O U R C E; KEY_STORE_PROVIDER_NAME: K E Y '_' S T O R E '_' P R O V I D E R '_' N A M E; KEYS: K E Y S; KEYSET: K E Y S E T; LANGUAGE: L A N G U A G E; LAST: L A S T; LEVEL: L E V E L; LIBRARY: L I B R A R Y; LIFETIME: L I F E T I M E; LINUX: L I N U X; LIST: L I S T; LISTENER_IP: L I S T E N E R '_' I P; LISTENER_PORT: L I S T E N E R '_' P O R T; LISTENER_URL: L I S T E N E R '_' U R L; LISTENER: L I S T E N E R; LOB_COMPACTION: L O B '_' C O M P A C T I O N; LOCAL_SERVICE_NAME: L O C A L '_' S E R V I C E '_' N A M E; LOCAL: L O C A L; LOCATION: L O C A T I O N; LOCK_ESCALATION: L O C K '_' E S C A L A T I O N; LOCK: L O C K; LOG: L O G; LOGIN: L O G I N; LOOP: L O O P; LOW: L O W; MANUAL: M A N U A L; MARK: M A R K; MASTER: M A S T E R; MATCHED: M A T C H E D; MATERIALIZED: M A T E R I A L I Z E D; MAX_CPU_PERCENT: M A X '_' C P U '_' P E R C E N T; MAX_DISPATCH_LATENCY: M A X '_' D I S P A T C H '_' L A T E N C Y; MAX_DOP: M A X '_' D O P; MAX_EVENT_SIZE: M A X '_' E V E N T '_' S I Z E; MAX_FILES: M A X '_' F I L E S; MAX_IOPS_PER_VOLUME: M A X '_' I O P S '_' P E R '_' V O L U M E; MAX_MEMORY_PERCENT: M A X '_' M E M O R Y '_' P E R C E N T; MAX_MEMORY: M A X '_' M E M O R Y; MAX_OUTSTANDING_IO_PER_VOLUME: M A X '_' O U T S T A N D I N G '_' I O '_' P E R '_' V O L U M E; MAX_PROCESSES: M A X '_' P R O C E S S E S; MAX_QUEUE_READERS: M A X '_' Q U E U E '_' R E A D E R S; MAX_ROLLOVER_FILES: M A X '_' R O L L O V E R '_' F I L E S; MAX_SIZE: M A X '_' S I Z E; MAX: M A X; MAXDOP: M A X D O P; MAX_DURATION: M A X '_' D U R A T I O N; MAXRECURSION: M A X R E C U R S I O N; MAXSIZE: M A X S I Z E; MAXTRANSFER: M A X T R A N S F E R; MAXVALUE: M A X V A L U E; MB: M B; MEDIADESCRIPTION: M E D I A D E S C R I P T I O N; MEDIANAME: M E D I A N A M E; MEDIUM: M E D I U M; MEMBER: M E M B E R; MEMORY_OPTIMIZED_DATA: M E M O R Y '_' O P T I M I Z E D '_' D A T A; MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT: M E M O R Y '_' O P T I M I Z E D '_' E L E V A T E '_' T O '_' S N A P S H O T; MEMORY_OPTIMIZED: M E M O R Y '_' O P T I M I Z E D; MEMORY_PARTITION_MODE: M E M O R Y '_' P A R T I T I O N '_' M O D E; MESSAGE_FORWARD_SIZE: M E S S A G E '_' F O R W A R D '_' S I Z E; MESSAGE_FORWARDING: M E S S A G E '_' F O R W A R D I N G; MESSAGE: M E S S A G E; MIN_ACTIVE_ROWVERSION: M I N '_' A C T I V E '_' R O W V E R S I O N; MIN_CPU_PERCENT: M I N '_' C P U '_' P E R C E N T; MIN_IOPS_PER_VOLUME: M I N '_' I O P S '_' P E R '_' V O L U M E; MIN_MEMORY_PERCENT: M I N '_' M E M O R Y '_' P E R C E N T; MINUTES: M I N U T E S; MINVALUE: M I N V A L U E; MIRROR_ADDRESS: M I R R O R '_' A D D R E S S; MIRROR: M I R R O R; MIXED_PAGE_ALLOCATION: M I X E D '_' P A G E '_' A L L O C A T I O N; MODE: M O D E; MODIFY: M O D I F Y; MOVE: M O V E; MULTI_USER: M U L T I '_' U S E R; MUST_CHANGE: M U S T '_' C H A N G E; NAME: N A M E; NCHAR: N C H A R; NEGOTIATE: N E G O T I A T E; NESTED_TRIGGERS: N E S T E D '_' T R I G G E R S; NEW_ACCOUNT: N E W '_' A C C O U N T; NEW_BROKER: N E W '_' B R O K E R; NEW_PASSWORD: N E W '_' P A S S W O R D; NEWNAME: N E W N A M E; NEXT: N E X T; NO_CHECKSUM: N O '_' C H E C K S U M; NO_COMPRESSION: N O '_' C O M P R E S S I O N; NO_EVENT_LOSS: N O '_' E V E N T '_' L O S S; NO_TRUNCATE: N O '_' T R U N C A T E; NO_WAIT: N O '_' W A I T; NO: N O; NODES: N O D E S; NOEXPAND: N O E X P A N D; NOFORMAT: N O F O R M A T; NOINIT: N O I N I T; NON_TRANSACTED_ACCESS: N O N '_' T R A N S A C T E D '_' A C C E S S; NONE: N O N E; NORECOMPUTE: N O R E C O M P U T E; NORECOVERY: N O R E C O V E R Y; NOREWIND: N O R E W I N D; NOSKIP: N O S K I P; NOTIFICATION: N O T I F I C A T I O N; NOUNLOAD: N O U N L O A D; NOWAIT: N O W A I T; NTLM: N T L M; NUMANODE: N U M A N O D E; NUMERIC_ROUNDABORT: N U M E R I C '_' R O U N D A B O R T; OBJECT: O B J E C T; OFFLINE: O F F L I N E; OFFSET: O F F S E T; OLD_ACCOUNT: O L D '_' A C C O U N T; OLD_PASSWORD: O L D '_' P A S S W O R D; ON_FAILURE: O N '_' F A I L U R E; ONLINE: O N L I N E; ONLY: O N L Y; OPEN_EXISTING: O P E N '_' E X I S T I N G; OPENJSON: O P E N J S O N; OPTIMISTIC: O P T I M I S T I C; OPTIMIZE: O P T I M I Z E; OUT: O U T; OUTPUT: O U T P U T; OWNER: O W N E R; PAGE_VERIFY: P A G E '_' V E R I F Y; PARAMETERIZATION: P A R A M E T E R I Z A T I O N; PARSE: (T R Y '_')? P A R S E; PARTIAL: P A R T I A L; PARTITION: P A R T I T I O N; PARTITIONS: P A R T I T I O N S; PARTNER: P A R T N E R; PASSWORD: P A S S W O R D; PATH: P A T H; PAUSE: P A U S E; PER_CPU: P E R '_' C P U; PER_DB: P E R '_' D B; PER_NODE: P E R '_' N O D E; PERMISSION_SET: P E R M I S S I O N '_' S E T; PERSIST_SAMPLE_PERSENT: P E R S I S T '_' S A M P L E '_' P E R S E N T; PERSISTED: P E R S I S T E D; PERSISTENT_LOG_BUFFER: P E R S I S T E N T '_' L O G '_' B U F F E R; PLATFORM: P L A T F O R M; POISON_MESSAGE_HANDLING: P O I S O N '_' M E S S A G E '_' H A N D L I N G; POLICY: P O L I C Y; POOL: P O O L; POPULATION: P O P U L A T I O N; PORT: P O R T; PRECEDING: P R E C E D I N G; PREDICATE: P R E D I C A T E; PRIMARY_ROLE: P R I M A R Y '_' R O L E; PRIOR: P R I O R; PRIORITY_LEVEL: P R I O R I T Y '_' L E V E L; PRIORITY: P R I O R I T Y; PRIVATE_KEY: P R I V A T E '_' K E Y; PRIVATE: P R I V A T E; PRIVILEGES: P R I V I L E G E S; PROCEDURE_NAME: P R O C E D U R E '_' N A M E; PROCESS: P R O C E S S; PROFILE: P R O F I L E; PROPERTY_DESCRIPTION: P R O P E R T Y '_' D E S C R I P T I O N; PROPERTY_INT_ID: P R O P E R T Y '_' I N T '_ ' I D; PROPERTY_SET_GUID: P R O P E R T Y '_' S E T '_ ' G U I D; PROPERTY: P R O P E R T Y; PROVIDER_KEY_NAME: P R O V I D E R '_' K E Y '_' N A M E; PROVIDER: P R O V I D E R; QUERYTRACEON: Q U E R Y T R A C E O N; QUEUE_DELAY: Q U E U E '_' D E L A Y; QUEUE: Q U E U E; QUOTED_IDENTIFIER: Q U O T E D '_' I D E N T I F I E R; R_LETTER: R; RANGE: R A N G E; RAW: R A W; RC2: R C '2'; RC4_128: R C '4' '_' '1' '2' '8'; RC4: R C '4'; READ_COMMITTED_SNAPSHOT: R E A D '_' C O M M I T T E D '_' S N A P S H O T; READ_ONLY_ROUTING_LIST: R E A D '_' O N L Y '_' R O U T I N G '_' L I S T; READ_ONLY: R E A D '_' O N L Y; READ_WRITE_FILEGROUPS: R E A D '_' W R I T E '_' F I L E G R O U P S; READ_WRITE: R E A D '_' W R I T E; READWRITE: R E A D W R I T E; READONLY: R E A D O N L Y; REBUILD: R E B U I L D; RECEIVE: R E C E I V E; RECOMPILE: R E C O M P I L E; RECOVERY: R E C O V E R Y; RECURSIVE_TRIGGERS: R E C U R S I V E '_' T R I G G E R S; REGENERATE: R E G E N E R A T E; RELATED_CONVERSATION_GROUP: R E L A T E D '_' C O N V E R S A T I O N '_' G R O U P; RELATED_CONVERSATION: R E L A T E D '_' C O N V E R S A T I O N; RELATIVE: R E L A T I V E; REMOTE_SERVICE_NAME: R E M O T E '_' S E R V I C E '_' N A M E; REMOTE: R E M O T E; REMOVE: R E M O V E; REORGANIZE: R E O R G A N I Z E; REPEATABLE: R E P E A T A B L E; REPLICA: R E P L I C A; REQUEST_MAX_CPU_TIME_SEC: R E Q U E S T '_' M A X '_' C P U '_' T I M E '_' S E C; REQUEST_MAX_MEMORY_GRANT_PERCENT: R E Q U E S T '_' M A X '_' M E M O R Y '_' G R A N T '_' P E R C E N T; REQUEST_MEMORY_GRANT_TIMEOUT_SEC: R E Q U E S T '_' M E M O R Y '_' G R A N T '_' T I M E O U T '_' S E C; REQUIRED_SYNCHRONIZED_SECONDARIES_TO_COMMIT: R E Q U I R E D '_' S Y N C H R O N I Z E D '_' S E C O N D A R I E S '_' T O '_' C O M M I T; REQUIRED: R E Q U I R E D; RESAMPLE: R E S A M P L E; RESERVE_DISK_SPACE: R E S E R V E '_' D I S K '_' S P A C E; RESET: R E S E T; RESOURCE_MANAGER_LOCATION: R E S O U R C E '_' M A N A G E R '_' L O C A T I O N; RESOURCE: R E S O U R C E; RESTART: R E S T A R T; RESTRICTED_USER: R E S T R I C T E D '_' U S E R; RESULT: R E S U L T; RESUME: R E S U M E; RETAINDAYS: R E T A I N D A Y S; RETENTION: R E T E N T I O N; RETURNS: R E T U R N S; REWIND: R E W I N D; ROBUST: R O B U S T; ROLE: R O L E; ROOT: R O O T; ROUTE: R O U T E; ROW: R O W; ROWGUID: R O W G U I D; ROWS: R O W S; RSA_1024: R S A '_' '1' '0' '2' '4'; RSA_2048: R S A '_' '2' '0' '4' '8'; RSA_3072: R S A '_' '3' '0' '7' '2'; RSA_4096: R S A '_' '4' '0' '9' '6'; RSA_512: R S A '_' '5' '1' '2'; SAFE: S A F E; SAFETY: S A F E T Y; SAMPLE: S A M P L E; SCHEDULER: S C H E D U L E R; SCHEMABINDING: S C H E M A B I N D I N G; SCHEME: S C H E M E; SCOPED: S C O P E D; SCROLL_LOCKS: S C R O L L '_' L O C K S; SCROLL: S C R O L L; SEARCH: S E A R C H; SECONDARY_ONLY: S E C O N D A R Y '_' O N L Y; SECONDARY_ROLE: S E C O N D A R Y '_' R O L E; SECONDARY: S E C O N D A R Y; SECONDS: S E C O N D S; SECRET: S E C R E T; SECURITY_LOG: S E C U R I T Y '_' L O G; SECURITY: S E C U R I T Y; SEEDING_MODE: S E E D I N G '_' M O D E; SELECTIVE: S E L E C T I V E; SELF: S E L F; SEMI_SENSITIVE: S E M I '_' S E N S I T I V E; SEND: S E N D; SENT: S E N T; SEQUENCE: S E Q U E N C E; SERIALIZABLE: S E R I A L I Z A B L E; SERVER: S E R V E R; SERVICE_BROKER: S E R V I C E '_' B R O K E R; SERVICE_NAME: S E R V I C E '_' N A M E; SERVICE: S E R V I C E; SESSION_TIMEOUT: S E S S I O N '_' T I M E O U T; SESSION: S E S S I O N; SETERROR: S E T E R R O R; SETS: S E T S; SHARE: S H A R E; SHOWPLAN: S H O W P L A N; SID: S I D; SIGNATURE: S I G N A T U R E; SIMPLE: S I M P L E; SINGLE_USER: S I N G L E '_' U S E R; SINGLETON: S I N G L E T O N; SIZE: S I Z E; SKIP_KEYWORD: S K I P; SNAPSHOT: S N A P S H O T; SOFTNUMA: S O F T N U M A; SOURCE: S O U R C E; SPARSE: S P A R S E; SPATIAL_WINDOW_MAX_CELLS: S P A T I A L '_' W I N D O W '_' M A X '_' C E L L S; SPECIFICATION: S P E C I F I C A T I O N; SPLIT: S P L I T; SQL: S Q L; SQLDUMPERFLAGS: S Q L D U M P E R F L A G S; SQLDUMPERPATH: S Q L D U M P E R P A T H; SQLDUMPERTIMEOUT: S Q L D U M P E R T I M E O U T; STANDBY: S T A N D B Y; START_DATE: S T A R T '_' D A T E; START: S T A R T; STARTED: S T A R T E D; STARTUP_STATE: S T A R T U P '_' S T A T E; STATE: S T A T E; STATIC: S T A T I C; STATISTICAL_SEMANTICS: S T A T I S T I C A L '_' S E M A N T I C S; STATS: S T A T S; STATUS: S T A T U S; STOP_ON_ERROR: S T O P '_' O N '_' E R R O R; STOP: S T O P; STOPLIST: S T O P L I S T; STOPPED: S T O P P E D; STRING_AGG: S T R I N G '_' A G G; SUBJECT: S U B J E C T; SUPPORTED: S U P P O R T E D; SUSPEND: S U S P E N D; SYMMETRIC: S Y M M E T R I C; SYNCHRONOUS_COMMIT: S Y N C H R O N O U S '_' C O M M I T; SYNONYM: S Y N O N Y M; SYSTEM: S Y S T E M; SWITCH: S W I T C H; TAKE: T A K E; TAPE: T A P E; TARGET_RECOVERY_TIME: T A R G E T '_' R E C O V E R Y '_' T I M E; TARGET: T A R G E T; TB: T B; TCP: T C P; TEXTIMAGE_ON: T E X T I M A G E '_' O N; THROW: T H R O W; TIES: T I E S; TIME: T I M E; TIMEOUT: T I M E O U T; TIMER: T I M E R; TORN_PAGE_DETECTION: T O R N '_' P A G E '_' D E T E C T I O N; TRACK_CAUSALITY: T R A C K '_' C A U S A L I T Y; TRACK_COLUMNS_UPDATED: T R A C K '_' C O L U M N S '_' U P D A T E D; TRANSFER: T R A N S F E R; TRANSFORM_NOISE_WORDS: T R A N S F O R M '_' N O I S E '_' W O R D S; TRIM: T R I M; TRIPLE_DES_3KEY: T R I P L E '_' D E S '_' '3' K E Y; TRIPLE_DES: T R I P L E '_' D E S; TRUE: T R U E; TRUSTWORTHY: T R U S T W O R T H Y; TRY: T R Y; TSQL: T S Q L; TWO_DIGIT_YEAR_CUTOFF: T W O '_' D I G I T '_' Y E A R '_' C U T O F F; TYPE_WARNING: T Y P E '_' W A R N I N G; TYPE: T Y P E; UNBOUNDED: U N B O U N D E D; UNCHECKED: U N C H E C K E D; UNCOMMITTED: U N C O M M I T T E D; UNDEFINED: U N D E F I N E D; UNKNOWN: U N K N O W N; UNLIMITED: U N L I M I T E D; UNLOCK: U N L O C K; UNSAFE: U N S A F E; URL: U R L; USED: U S E D; USING: U S I N G; VALID_XML: V A L I D '_' X M L; VALIDATION: V A L I D A T I O N; VALUE: V A L U E; VERBOSELOGGING: V E R B O S E L O G G I N G; VERSION: V E R S I O N; VIEW_METADATA: V I E W '_' M E T A D A T A; VIEWS: V I E W S; VISIBILITY: V I S I B I L I T Y; WAIT: W A I T; WAIT_AT_LOW_PRIORITY: W A I T '_' A T '_' L O W '_' P R I O R I T Y ; WELL_FORMED_XML: W E L L '_' F O R M E D '_' X M L; WINDOWS: W I N D O W S; WITHOUT_ARRAY_WRAPPER: W I T H O U T '_' A R R A Y '_' W R A P P E R; WITHOUT: W I T H O U T; WITNESS: W I T N E S S; WORK: W O R K; WORKLOAD: W O R K L O A D; XML: X M L; XMLDATA: X M L D A T A; XMLNAMESPACES: X M L N A M E S P A C E S; XMLSCHEMA: X M L S C H E M A; XQUERY: X Q U E R Y; XSINIL: X S I N I L; // last identifier rule, sync with CustomTSQLAntlrErrorStrategy // https://docs.microsoft.com/en-us/sql/t-sql/language-elements/slash-star-comment-transact-sql COMMENT: '/*' (COMMENT | .)*? '*/' -> channel(HIDDEN); LINE_COMMENT: '--' ~[\\r\\n]* -> channel(HIDDEN); // TODO: ID can be not only Latin. LEFT_FIGURE_PAREN: '{'; RIGHT_FIGURE_PAREN: '}'; DOUBLE_QUOTE_ID: UnterminatedQuotedIdentifier '""' // unquote so that we may always call getText() and not worry about quotes { String __tx = getText(); setText(__tx.substring(1, __tx.length() - 1).replace(""\\""\\"""", ""\\"""")); } ; SINGLE_QUOTE: '\\''; SQUARE_BRACKET_ID: UnterminatedSquareQuotedIdentifier ']' // unquote so that we may always call getText() and not worry about quotes { String __tx = getText(); setText(__tx.substring(1, __tx.length() - 1).replace(""]]"", ""]"")); } ; LOCAL_ID: '@' ([a-zA-Z_$@#0-9] | FullWidthLetter)+; DECIMAL: DEC_DIGIT+; ID: ( [a-zA-Z_#] | FullWidthLetter) ( [a-zA-Z_#$@0-9] | FullWidthLetter )*; STRING: N? '\\'' (~'\\'' | '\\'\\'')* '\\''; BINARY: '0' X (HEX_DIGIT | BACKSLASH [\\r]? [\\n])*; FLOAT: DEC_DOT_DEC; REAL: (DECIMAL | DEC_DOT_DEC) (E [+-]? DEC_DIGIT+); IPV4_ADDR: IPV4_OCTECT DOT IPV4_OCTECT DOT IPV4_OCTECT DOT IPV4_OCTECT; // TODO doesn't support IPV6 zero compression IPV6_ADDR: HEX_DIGIT? HEX_DIGIT? HEX_DIGIT? HEX_DIGIT [:] HEX_DIGIT? HEX_DIGIT? HEX_DIGIT? HEX_DIGIT [:] HEX_DIGIT? HEX_DIGIT? HEX_DIGIT? HEX_DIGIT [:] HEX_DIGIT? HEX_DIGIT? HEX_DIGIT? HEX_DIGIT [:] HEX_DIGIT? HEX_DIGIT? HEX_DIGIT? HEX_DIGIT [:] HEX_DIGIT? HEX_DIGIT? HEX_DIGIT? HEX_DIGIT [:] HEX_DIGIT? HEX_DIGIT? HEX_DIGIT? HEX_DIGIT [:] HEX_DIGIT? HEX_DIGIT? HEX_DIGIT? HEX_DIGIT; BACKSLASH: '\\\\'; DOUBLE_FORWARD_SLASH:'//'; EQUAL: '='; GREATER: '>'; LESS: '<'; EXCLAMATION: '!'; PLUS_ASSIGN: '+='; MINUS_ASSIGN: '-='; MULT_ASSIGN: '*='; DIV_ASSIGN: '/='; MOD_ASSIGN: '%='; AND_ASSIGN: '&='; XOR_ASSIGN: '^='; OR_ASSIGN: '|='; DOT: '.'; AT: '@'; DOLLAR: '$'; LR_BRACKET: '('; RR_BRACKET: ')'; COMMA: ','; SEMI: ';'; COLON: ':'; STAR: '*'; DIVIDE: '/'; MODULE: '%'; PLUS: '+'; MINUS: '-'; BIT_NOT: '~'; BIT_OR: '|'; BIT_AND: '&'; BIT_XOR: '^'; // This is a quoted identifier which only contains valid characters but is not terminated fragment UnterminatedQuotedIdentifier : '""' ( '""""' | ~[\\u0000""] )* ; // This is a quoted identifier which only contains valid characters but is not terminated fragment UnterminatedSquareQuotedIdentifier : '[' ( ']]' | ~[\\u0000\\]] )* ; fragment IPV4_OCTECT: [0-9]?[0-9]?[0-9]; fragment DEC_DOT_DEC: (DEC_DIGIT+ '.' DEC_DIGIT+ | DEC_DIGIT+ '.' | '.' DEC_DIGIT+); fragment HEX_DIGIT: [0-9A-Fa-f]; fragment DEC_DIGIT: [0-9]; fragment A: [aA]; fragment B: [bB]; fragment C: [cC]; fragment D: [dD]; fragment E: [eE]; fragment F: [fF]; fragment G: [gG]; fragment H: [hH]; fragment I: [iI]; fragment J: [jJ]; fragment K: [kK]; fragment L: [lL]; fragment M: [mM]; fragment N: [nN]; fragment O: [oO]; fragment P: [pP]; fragment Q: [qQ]; fragment R: [rR]; fragment S: [sS]; fragment T: [tT]; fragment U: [uU]; fragment V: [vV]; fragment W: [wW]; fragment X: [xX]; fragment Y: [yY]; fragment Z: [zZ]; fragment FullWidthLetter : '\\u00c0'..'\\u00d6' | '\\u00d8'..'\\u00f6' | '\\u00f8'..'\\u00ff' | '\\u0100'..'\\u1fff' | '\\u2c00'..'\\u2fff' | '\\u3040'..'\\u318f' | '\\u3300'..'\\u337f' | '\\u3400'..'\\u3fff' | '\\u4e00'..'\\u9fff' | '\\ua000'..'\\ud7ff' | '\\uf900'..'\\ufaff' | '\\uff00'..'\\ufff0' // | '\\u10000'..'\\u1F9FF' //not support four bytes chars // | '\\u20000'..'\\u2FA1F' ; BOM: '\\ufeff'; SPACE: [ \\t\\r\\n]+ -> skip; BAD : . ; ",12500,True,2622.211224920151,median "<%-- // // DefaultWsdlHelpGenerator.aspx: // // Author: // Lluis Sanchez Gual (lluis@ximian.com) // // (C) 2003 Ximian, Inc. http://www.ximian.com // --%> <%@ Import Namespace=""System.Collections"" %> <%@ Import Namespace=""System.IO"" %> <%@ Import Namespace=""System.Xml.Serialization"" %> <%@ Import Namespace=""System.Xml"" %> <%@ Import Namespace=""System.Xml.Schema"" %> <%@ Import Namespace=""System.Web.Services.Description"" %> <%@ Import Namespace=""System"" %> <%@ Import Namespace=""System.Net"" %> <%@ Import Namespace=""System.Globalization"" %> <%@ Import Namespace=""System.Resources"" %> <%@ Import Namespace=""System.Diagnostics"" %> <%@ Import Namespace=""System.CodeDom"" %> <%@ Import Namespace=""System.CodeDom.Compiler"" %> <%@ Import Namespace=""Microsoft.CSharp"" %> <%@ Import Namespace=""Microsoft.VisualBasic"" %> <%@ Import Namespace=""System.Text"" %> <%@ Import Namespace=""System.Text.RegularExpressions"" %> <%@ Import Namespace=""System.Security.Cryptography.X509Certificates"" %> <%@ Assembly name=""System.Web.Services"" %> <%@ Page debug=""true"" %> ?disco""/> <%=WebServiceName%> Web Service
    Web Service
    <%=WebServiceName%>
    Overview
    Service Description
    Client proxy

    <%#FormatBindingName(DataBinder.Eval(Container.DataItem, ""Name"").ToString())%> ?<%=GetTabContext(""op"",null)%>op=<%#GetOpName(Container.DataItem)%>&bnd=<%#DataBinder.Eval(Container.DataItem, ""Binding.Name"")%>""><%#GetOpName(Container.DataItem)%>

    <% if (CurrentPage == ""main"") {%>

    Web Service Overview

    <%=WebServiceDescription%> <%} if (DefaultBinding == null) {%> This service does not contain any public web method. <%} else if (CurrentPage == ""op"") {%> <%=CurrentOperationName%>

    <% WriteTabs (); %>


    <% if (CurrentTab == ""main"") { %> Input Parameters
    <% if (InParams.Count == 0) { %> No input parameters
    <% } else { %>
    <%#DataBinder.Eval(Container.DataItem, ""Name"")%> <%#DataBinder.Eval(Container.DataItem, ""Type"")%>
    <% } %>
    <% if (OutParams.Count > 0) { %> Output Parameters
    <%#DataBinder.Eval(Container.DataItem, ""Name"")%> <%#DataBinder.Eval(Container.DataItem, ""Type"")%>

    <% } %> Remarks
    <%=OperationDocumentation%>

    Technical information
    Format: <%=CurrentOperationFormat%>
    Supported protocols: <%=CurrentOperationProtocols%> <% } %> <% if (CurrentTab == ""test"") { if (CurrentOperationSupportsTest) {%> Enter values for the parameters and click the 'Invoke' button to test this method:

    "" method=""GET""> ""> ""> ""> "">
    <%#DataBinder.Eval(Container.DataItem, ""Name"")%>:  "">
     
    ""> The web service returned the following result:

    <%=GetTestResult()%>
    <% } else {%> The test form is not available for this operation because it has parameters with a complex structure. <% } %> <% } %> <% if (CurrentTab == ""msg"") { %> The following are sample SOAP requests and responses for each protocol supported by this method:

    <% if (IsOperationSupported (""Soap"")) { %> Soap

    <%=GenerateOperationMessages (""Soap"", true)%>

    <%=GenerateOperationMessages (""Soap"", false)%>

    <% } %> <% if (IsOperationSupported (""HttpGet"")) { %> HTTP Get

    <%=GenerateOperationMessages (""HttpGet"", true)%>

    <%=GenerateOperationMessages (""HttpGet"", false)%>

    <% } %> <% if (IsOperationSupported (""HttpPost"")) { %> HTTP Post

    <%=GenerateOperationMessages (""HttpPost"", true)%>

    <%=GenerateOperationMessages (""HttpPost"", false)%>

    <% } %> <% } %> <%} else if (CurrentPage == ""proxy"") {%>
    "" name=""langForm"" method=""GET""> Select the language for which you want to generate a proxy "">    

    <%=CurrentProxytName%>    "">Download

    ""><%=GetProxyCode ()%>
    <%} else if (CurrentPage == ""wsdl"") {%> <% if (descriptions.Count > 1 || schemas.Count > 1) {%> The description of this web service is composed by several documents. Click on the document you want to see: <%} else {%> <%}%>
    <%=CurrentDocumentName%>    "">Download

    <%=GenerateDocument ()%>
    <%}%>














    ",16349,True,2562.006668639574,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * When false, CREATE TABLE syntax without a provider will use * the value of spark.sql.sources.default as its provider. */ public boolean legacy_create_hive_table_by_default_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; /** * This method will be called when we see '/*' and try to match it as a bracketed comment. * If the next character is '+', it should be parsed as hint later, and we cannot match * it as a bracketed comment. * * Returns true if the next character is '+'. */ public boolean isHint() { int nextChar = _input.LA(1); if (nextChar == '+') { return true; } else { return false; } } } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE namespace (IF NOT EXISTS)? multipartIdentifier (commentSpec | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER namespace multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER namespace multipartIdentifier SET locationSpec #setNamespaceLocation | DROP namespace (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | {!legacy_create_hive_table_by_default_enabled}? createTableHeader ('(' colTypeList ')')? tableProvider? createTableClauses (AS? query)? #createTable | {legacy_create_hive_table_by_default_enabled}? createTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (commentSpec | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties |ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier alterColumnAction? #alterTableAlterColumn | ALTER TABLE table=multipartIdentifier partitionSpec? CHANGE COLUMN? colName=multipartIdentifier colType colPosition? #hiveChangeColumn | ALTER TABLE table=multipartIdentifier partitionSpec? REPLACE COLUMNS '(' columns=qualifiedColTypeWithPositionList ')' #hiveReplaceColumns | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? (commentSpec | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) ns=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) ns=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier (AS SERDE)? #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) namespace EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeRelation | (DESC | DESCRIBE) QUERY? query #describeQuery | COMMENT ON namespace multipartIdentifier IS comment=(STRING | NULL) #commentNamespace | COMMENT ON TABLE multipartIdentifier IS comment=(STRING | NULL) #commentTable | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier (STRING | .*?) #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; commentSpec : COMMENT STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; namespace : NAMESPACE | DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; createTableClauses :((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | commentSpec | (TBLPROPERTIES tableProps=tablePropertyList))* ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier commentSpec? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=RLIKE pattern=valueExpression | NOT? kind=LIKE pattern=valueExpression (ESCAPE escapeChar=STRING)? | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | FIRST '(' expression (IGNORE NULLS)? ')' #first | LAST '(' expression (IGNORE NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (FILTER '(' WHERE where=booleanExpression ')')? (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | HOUR | MINUTE | MONTH | SECOND | YEAR | identifier ; colPosition : position=FIRST | position=AFTER afterCol=errorCapturingIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (NOT NULL)? commentSpec? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (NOT NULL)? commentSpec? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (NOT NULL)? commentSpec? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | FILTER | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; alterColumnAction : TYPE dataType | commentSpec | colPosition | setOrDrop=(SET | DROP) NOT NULL ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `EXPLAIN SELECT ...` is a command, but EXPLAIN // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WINDOW ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPE | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FILTER | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MINUTE | MONTH | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WHEN | WHERE | WINDOW | WITH | YEAR ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILTER: 'FILTER'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' {!isHint()}? (BRACKETED_COMMENT|.)*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12502,False,2338.8338616821543,median "<%@ Page Title="""" Language=""C#"" Theme=""ThemeBlue"" MasterPageFile=""~/Pages/Site1.Master"" AutoEventWireup=""true"" CodeBehind=""Sales.aspx.cs"" Inherits=""OnLine.Pages.Sales"" %>
    All Leads

    All Leads

    Filter By

    Lead#:  Category:   Active Status:  Customer:

    From Date (Due) :    To Date (Due) :   Assigned To:      

    <%-- --%> Show! Show! Show!
                 

      

    All Potentials

    All Potentials

    Filter By

    Pot#:  Category:   Potential Stage:   Actvie Status:  Customer:  

    From Date (Due) :  To Date (Due) :

    From Date (Create) :  To Date (Create) :  Assigned To:       


    Show! Show!     "" Text='<%# Eval(""PO_Id"") %>' onclientclick=""javascript:unSelrdbtn()""> Show!  
                   


    All Invoices Sent By Us

    All Invoices Sent By Us

    Filter By

    RFQ#:  Invoice No:  Transaction No:

    Category:  Delivery Status:  Payment Status:  Customer: 

    Invoice Date (From) :    Invoice Date (To) :      



    Show!     Show! Show!

           

     

    All Sales Orders

    All Sales Orders

    Filter By

    RFQ#:  SO No:  Customer: 

    SO Date (From) :    SO Date (To) :      

    "" onclientclick=""javascript:unSelrdbtn()"" oncommand=""LinkButton_SO_Purchase_Order_Command"" Text='<%# Eval(""SO_No"") %>'>


       


    ",16311,True,4376.236321442808,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, ANSI SQL parsing mode is enabled. */ public boolean ansi = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; singleInterval : INTERVAL? multiUnitsInterval EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER (database | NAMESPACE) multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER database db=errorCapturingIdentifier SET locationSpec #setDatabaseLocation | DROP (database | NAMESPACE) (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier tableProvider? locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) namespace=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) namespace=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) (database | NAMESPACE) EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | negativeSign=MINUS? identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : negativeSign=MINUS? INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? | {ansi}? (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval) ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER multipartIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!ansi}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {ansi}? ansiNonReserved #unquotedIdentifier | {!ansi}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `spark.sql.dialect.spark.ansi.enabled=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `spark.sql.dialect.spark.ansi.enabled=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `spark.sql.dialect.spark.ansi.enabled=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12367,False,2315.6013788324317,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, ANSI SQL parsing mode is enabled. */ public boolean ansi = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; singleInterval : INTERVAL? multiUnitsInterval EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER database db=errorCapturingIdentifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | ALTER database db=errorCapturingIdentifier SET locationSpec #setDatabaseLocation | DROP (database | NAMESPACE) (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE multipartIdentifier RENAME COLUMN from=qualifiedName TO to=identifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=qualifiedNameList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=qualifiedNameList #dropTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE multipartIdentifier (ALTER | CHANGE) COLUMN? qualifiedName (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE tableIdentifier partitionSpec? CHANGE COLUMN? colName=errorCapturingIdentifier colType colPosition? #changeColumn | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER TABLE tableIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER VIEW tableIdentifier ADD (IF NOT EXISTS)? partitionSpec+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW tableIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? qualifiedName AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? qualifiedName #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=errorCapturingIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) namespace=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (qualifiedName | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) database EXTENDED? db=errorCapturingIdentifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING qualifiedName ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assign (',' assign)* ; assign : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | IDENTIFIER '->' expression #lambda | '(' IDENTIFIER (',' IDENTIFIER)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? | {ansi}? (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval) ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER qualifiedName ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=qualifiedName dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!ansi}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {ansi}? ansiNonReserved #unquotedIdentifier | {!ansi}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `spark.sql.ansi.enabled=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `spark.sql.ansi.enabled=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `spark.sql.ansi.enabled=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12134,False,2273.9390340096397,median "<%@ Control Language=""C#"" AutoEventWireup=""true"" CodeFile=""ctl_ManageUser.ascx.cs"" Inherits=""SageFrame.Modules.Admin.UserManagement.ctl_ManageUser"" %> <%@ Register Assembly=""AjaxControlToolkit"" Namespace=""AjaxControlToolkit"" TagPrefix=""ajax"" %>

     

    User Info

    Male Female

    Contacts

    User Info

    Contacts

    <%----%> Add User

      All * are required fields

    *
    *
    *
    *
    *

    *
    *
    *
    *

    10 25 50 100 150 200 250
    <%#Container.DataItemIndex+1 %> <%# Eval(""FirstName"")%> <%# Eval(""LastName"")%> <%# Eval(""Email"")%>

    Allow Duplicate UserNames Across Portals
    Allow Duplicate Email
    Enable Duplicate Roles Across Portals
    Enable Captcha For User Registration
    One Way Hashed Encrypted

    User Import

    UserName :
    First Name :
    Last Name :
    Email :
    Password :
    Password Salt :
    Password Format :
    Role Name :
    PortalID :
    IsActive :
    ",16316,True,3836.7061203515655,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * When false, a literal with an exponent would be converted into * double type rather than decimal type. */ public boolean legacy_exponent_literal_as_decimal_enabled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, the behavior of keywords follows ANSI SQL standard. */ public boolean SQL_standard_keyword_behavior = false; } singleStatement : statement ';'* EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE namespace (IF NOT EXISTS)? multipartIdentifier (commentSpec | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER namespace multipartIdentifier SET (DBPROPERTIES | PROPERTIES) tablePropertyList #setNamespaceProperties | ALTER namespace multipartIdentifier SET locationSpec #setNamespaceLocation | DROP namespace (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? (commentSpec | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier (tableProvider | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider createTableClauses (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=multipartIdentifier RENAME TO to=multipartIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier alterColumnAction? #alterTableAlterColumn | ALTER TABLE table=multipartIdentifier partitionSpec? CHANGE COLUMN? colName=multipartIdentifier colType colPosition? #hiveChangeColumn | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? multipartIdentifier identifierCommentList? (commentSpec | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) ns=multipartIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=multipartIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) ns=multipartIdentifier)? #showColumns | SHOW VIEWS ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showViews | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier (AS SERDE)? #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) namespace EXTENDED? multipartIdentifier #describeNamespace | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeRelation | (DESC | DESCRIBE) QUERY? query #describeQuery | COMMENT ON namespace multipartIdentifier IS comment=(STRING | NULL) #commentNamespace | COMMENT ON TABLE multipartIdentifier IS comment=(STRING | NULL) #commentTable | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier (STRING | .*?) #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; commentSpec : COMMENT STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; namespace : NAMESPACE | DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; createTableClauses :((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | commentSpec | (TBLPROPERTIES tableProps=tablePropertyList))* ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier commentSpec? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=RLIKE pattern=valueExpression | NOT? kind=LIKE pattern=valueExpression (ESCAPE escapeChar=STRING)? | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | FIRST '(' expression (IGNORE NULLS)? ')' #first | LAST '(' expression (IGNORE NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | functionName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (FILTER '(' WHERE where=booleanExpression ')')? (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | HOUR | MINUTE | MONTH | SECOND | YEAR | identifier ; colPosition : position=FIRST | position=AFTER afterCol=errorCapturingIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (NOT NULL)? commentSpec? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (NOT NULL)? commentSpec? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (NOT NULL)? commentSpec? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; functionName : qualifiedName | FILTER | LEFT | RIGHT ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!SQL_standard_keyword_behavior}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {SQL_standard_keyword_behavior}? ansiNonReserved #unquotedIdentifier | {!SQL_standard_keyword_behavior}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : {!legacy_exponent_literal_as_decimal_enabled}? MINUS? EXPONENT_VALUE #exponentLiteral | {!legacy_exponent_literal_as_decimal_enabled}? MINUS? DECIMAL_VALUE #decimalLiteral | {legacy_exponent_literal_as_decimal_enabled}? MINUS? (EXPONENT_VALUE | DECIMAL_VALUE) #legacyDecimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; alterColumnAction : TYPE dataType | commentSpec | colPosition | setOrDrop=(SET | DROP) NOT NULL ; // When `SQL_standard_keyword_behavior=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `EXPLAIN SELECT ...` is a command, but EXPLAIN // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved //--ANSI-NON-RESERVED-START : ADD | AFTER | ALTER | ANALYZE | ANTI | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SEMI | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETMINUS | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | VIEWS | WINDOW //--ANSI-NON-RESERVED-END ; // When `SQL_standard_keyword_behavior=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `SQL_standard_keyword_behavior=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved //--DEFAULT-NON-RESERVED-START : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPE | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FILTER | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MINUTE | MONTH | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | VIEWS | WHEN | WHERE | WINDOW | WITH | YEAR //--DEFAULT-NON-RESERVED-END ; // NOTE: If you add a new token in the list below, you should update the list of keywords // and reserved tag in `docs/sql-ref-ansi-compliance.md#sql-keywords`. //============================ // Start of the keywords list //============================ //--SPARK-KEYWORD-LIST-START ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DIV: 'DIV'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPE: 'ESCAPE'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILTER: 'FILTER'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MINUTE: 'MINUTE'; MONTH: 'MONTH'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; VIEWS: 'VIEWS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; //--SPARK-KEYWORD-LIST-END //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; EXPONENT_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT {isValidDecimal()}? ; DECIMAL_VALUE : DECIMAL_DIGITS {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ('\\\\\\n' | ~[\\r\\n])* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12377,False,2297.000817201989,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, ANSI SQL parsing mode is enabled. */ public boolean ansi = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER database db=errorCapturingIdentifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | ALTER database db=errorCapturingIdentifier SET locationSpec #setDatabaseLocation | DROP database (IF EXISTS)? db=errorCapturingIdentifier (RESTRICT | CASCADE)? #dropDatabase | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE multipartIdentifier RENAME COLUMN from=qualifiedName TO to=identifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=qualifiedNameList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=qualifiedNameList #dropTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE multipartIdentifier (ALTER | CHANGE) COLUMN? qualifiedName (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE tableIdentifier partitionSpec? CHANGE COLUMN? colName=errorCapturingIdentifier colType colPosition? #changeColumn | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE tableIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER TABLE tableIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER VIEW tableIdentifier ADD (IF NOT EXISTS)? partitionSpec+ #addTablePartition | ALTER TABLE tableIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER TABLE tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER VIEW tableIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* #dropTablePartitions | ALTER TABLE multipartIdentifier SET locationSpec #setTableLocation | ALTER TABLE tableIdentifier partitionSpec SET locationSpec #setPartitionLocation | ALTER TABLE tableIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW tableIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? qualifiedName AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? qualifiedName #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=errorCapturingIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) tableIdentifier ((FROM | IN) db=errorCapturingIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (qualifiedName | pattern=STRING))? #showFunctions | SHOW CREATE TABLE tableIdentifier #showCreateTable | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) database EXTENDED? db=errorCapturingIdentifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE tableIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE tableIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? tableIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE tableIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING qualifiedName ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assign (',' assign)* ; assign : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | IDENTIFIER '->' expression #lambda | '(' IDENTIFIER (',' IDENTIFIER)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : {ansi}? INTERVAL? intervalField+ | {!ansi}? INTERVAL intervalField* ; intervalField : value=intervalValue unit=intervalUnit (TO to=intervalUnit)? ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER qualifiedName ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=qualifiedName dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!ansi}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {ansi}? ansiNonReserved #unquotedIdentifier | {!ansi}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `spark.sql.ansi.enabled=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `spark.sql.ansi.enabled=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `spark.sql.ansi.enabled=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12064,False,2246.2634809781202,median "<%@ Control Language=""C#"" %> <%@ Register Assembly=""Telerik.Web.UI"" Namespace=""Telerik.Web.UI.Editor"" TagPrefix=""tools"" %> <%@ Register Assembly=""Telerik.Web.UI"" Namespace=""Telerik.Web.UI.Widgets"" TagPrefix=""widgets"" %> <%@ Register Assembly=""Telerik.Web.UI"" Namespace=""Telerik.Web.UI.Dialogs"" TagPrefix=""dialogs"" %> <%@ Register Assembly=""Telerik.Web.UI"" Namespace=""Telerik.Web.UI"" TagPrefix=""telerik"" %>
    px px
    px px
    ",16317,True,2591.8258235428652,median "<%@ Page Language=""C#"" AutoEventWireup=""true"" CodeFile=""insurance.aspx.cs"" Inherits=""insurance"" %> Naruvi Hospitals

    Careers

    About Naruvi

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. example@gmail.com

    Vacant Positions

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Experience :

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Experience :

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    Experience :

    72/1B2, Collector Office Road, Bangalore - Chennai National Highway (NH 48), Vellore – 632 004. info@naruvi.com

    © 2021 Naruvi Hospitals

    - Apply Now -

    8 d n p C I U
    <%-- --%>

    - Book an Appointment -

    <%-- --%> Enter your name
    <%-- --%> Enter your email id Enter your Valid email id
    <%-- --%> Enter your mobile number
    Enter your date of birth Enter date of birth in dd/mm/yyyy format ONLY.
    Select department
    Select doctor
    - Day - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 <%----%> choose appointment date Enter the valid day
    - Month - January Febuary March April May June July August September October November December choose appointment month
    - Year - 2021 <%-- --%> choose appointment year
    Choose your appointment date Enter valid appointment date
    choose appointment time
    <%-- --%> Enter your purpose of appointment
    <%-- --%>
    Enter verification code Enter valid verification code
    <%-- --%>
    ×
    Thank you for your appointment request. We will get back to you on the status of your appointment.
    ",16143,False,2229.888727044228,median "<%@ Control Language=""c#"" AutoEventWireup=""True"" Codebehind=""EditConfigBox.ascx.cs"" Inherits=""newtelligence.DasBlog.Web.EditConfigBox"" TargetSchema=""http://schemas.microsoft.com/intellisense/ie5"" %>
    *
    **
    **
    *
    *  
    <%# resmgr.GetString(""text_days_expire_field"")%>
      
    <%# resmgr.GetString(""text_gravatar_field"")%>
    G PG R X
    <%# resmgr.GetString(""text_config_georss"")%>
    *
    *
     
    *
    <%# resmgr.GetString(""text_comments_html_field"")%>
    **
    *
    **
    **

     
     
     
    *
    *
    *

    **
    **
    **

    *
    *    
    *
        **
    *
    *  
    *

    ",16361,True,4149.50941786181,median "/* * Copyright (C) 2017, Ulrich Wolffgang * All rights reserved. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ parser grammar CobolParser; options {tokenVocab = CobolLexer;} import CICSParser; startRule : compilationUnit EOF; compilationUnit : programUnit+ ; programUnit : identificationDivision environmentDivision? dataDivision? procedureDivision? programUnit* endProgramStatement? ; endProgramStatement : END PROGRAM programName DOT_FS ; // --- identification division -------------------------------------------------------------------- identificationDivision : (IDENTIFICATION | ID) DIVISION DOT_FS programIdParagraph identificationDivisionBody* ; identificationDivisionBody : authorParagraph | installationParagraph | dateWrittenParagraph | dateCompiledParagraph | securityParagraph ; // - program id paragraph ---------------------------------- programIdParagraph : PROGRAM_ID DOT_FS programName (IS? (COMMON | INITIAL | LIBRARY | DEFINITION | RECURSIVE) PROGRAM?)? DOT_FS? commentEntry? ; // - author paragraph ---------------------------------- authorParagraph : AUTHOR DOT_FS commentEntry? ; // - installation paragraph ---------------------------------- installationParagraph : INSTALLATION DOT_FS commentEntry? ; // - date written paragraph ---------------------------------- dateWrittenParagraph : DATE_WRITTEN DOT_FS commentEntry? ; // - date compiled paragraph ---------------------------------- dateCompiledParagraph : DATE_COMPILED DOT_FS commentEntry? ; // - security paragraph ---------------------------------- securityParagraph : SECURITY DOT_FS commentEntry? ; // --- environment division -------------------------------------------------------------------- environmentDivision : ENVIRONMENT DIVISION DOT_FS environmentDivisionBody* ; environmentDivisionBody : configurationSection | specialNamesParagraph | inputOutputSection ; // -- configuration section ---------------------------------- configurationSection : CONFIGURATION SECTION DOT_FS configurationSectionParagraph* ; // - configuration section paragraph ---------------------------------- configurationSectionParagraph : sourceComputerParagraph | objectComputerParagraph | specialNamesParagraph // strictly, specialNamesParagraph does not belong into configurationSectionParagraph, but IBM-COBOL allows this ; // - source computer paragraph ---------------------------------- sourceComputerParagraph : SOURCE_COMPUTER DOT_FS (computerName (WITH? DEBUGGING MODE)? DOT_FS)? ; // - object computer paragraph ---------------------------------- objectComputerParagraph : OBJECT_COMPUTER DOT_FS (computerName objectComputerClause* DOT_FS)? ; objectComputerClause : memorySizeClause | diskSizeClause | collatingSequenceClause | segmentLimitClause | characterSetClause ; memorySizeClause : MEMORY SIZE? (integerLiteral | cobolWord) (WORDS | CHARACTERS | MODULES)? ; diskSizeClause : DISK SIZE? IS? (integerLiteral | cobolWord) (WORDS | MODULES)? ; collatingSequenceClause : PROGRAM? COLLATING? SEQUENCE (IS? alphabetName+) collatingSequenceClauseAlphanumeric? collatingSequenceClauseNational? ; collatingSequenceClauseAlphanumeric : FOR? ALPHANUMERIC IS? alphabetName ; collatingSequenceClauseNational : FOR? NATIONAL IS? alphabetName ; segmentLimitClause : SEGMENT_LIMIT IS? integerLiteral ; characterSetClause : CHARACTER SET DOT_FS ; // - special names paragraph ---------------------------------- specialNamesParagraph : SPECIAL_NAMES DOT_FS (specialNameClause+ DOT_FS)? ; specialNameClause : channelClause | odtClause | alphabetClause | classClause | currencySignClause | decimalPointClause | symbolicCharactersClause | environmentSwitchNameClause | defaultDisplaySignClause | defaultComputationalSignClause | reserveNetworkClause ; alphabetClause : alphabetClauseFormat1 | alphabetClauseFormat2 ; alphabetClauseFormat1 : ALPHABET alphabetName (FOR ALPHANUMERIC)? IS? (EBCDIC | ASCII | STANDARD_1 | STANDARD_2 | NATIVE | cobolWord | alphabetLiterals+) ; alphabetLiterals : literal (alphabetThrough | alphabetAlso+)? ; alphabetThrough : (THROUGH | THRU) literal ; alphabetAlso : ALSO literal+ ; alphabetClauseFormat2 : ALPHABET alphabetName FOR? NATIONAL IS? (NATIVE | CCSVERSION literal) ; channelClause : CHANNEL integerLiteral IS? mnemonicName ; classClause : CLASS className (FOR? (ALPHANUMERIC | NATIONAL))? IS? classClauseThrough+ ; classClauseThrough : classClauseFrom ((THROUGH | THRU) classClauseTo)? ; classClauseFrom : literal | generalIdentifier ; classClauseTo : literal | generalIdentifier ; currencySignClause : CURRENCY SIGN? IS? literal (WITH? PICTURE SYMBOL literal)? ; decimalPointClause : DECIMAL_POINT IS? COMMA ; defaultComputationalSignClause : DEFAULT (COMPUTATIONAL | COMP)? (SIGN IS?)? (LEADING | TRAILING)? (SEPARATE CHARACTER?) ; defaultDisplaySignClause : DEFAULT_DISPLAY (SIGN IS?)? (LEADING | TRAILING) (SEPARATE CHARACTER?)? ; environmentSwitchNameClause : environmentName IS? mnemonicName environmentSwitchNameSpecialNamesStatusPhrase? | environmentSwitchNameSpecialNamesStatusPhrase ; environmentSwitchNameSpecialNamesStatusPhrase : ON STATUS? IS? condition (OFF STATUS? IS? condition)? | OFF STATUS? IS? condition (ON STATUS? IS? condition)? ; odtClause : ODT IS? mnemonicName ; reserveNetworkClause : RESERVE WORDS? LIST? IS? NETWORK CAPABLE? ; symbolicCharactersClause : SYMBOLIC CHARACTERS? (FOR? (ALPHANUMERIC | NATIONAL))? symbolicCharacters+ (IN alphabetName)? ; symbolicCharacters : symbolicCharacter+ (IS | ARE)? integerLiteral+ ; // -- input output section ---------------------------------- inputOutputSection : INPUT_OUTPUT SECTION DOT_FS inputOutputSectionParagraph* ; // - input output section paragraph ---------------------------------- inputOutputSectionParagraph : fileControlParagraph | ioControlParagraph ; // - file control paragraph ---------------------------------- fileControlParagraph : FILE_CONTROL? (DOT_FS? fileControlEntry)* DOT_FS ; fileControlEntry : selectClause fileControlClause* ; selectClause : SELECT OPTIONAL? fileName ; fileControlClause : assignClause | reserveClause | organizationClause | paddingCharacterClause | recordDelimiterClause | accessModeClause | recordKeyClause | alternateRecordKeyClause | fileStatusClause | passwordClause | relativeKeyClause ; assignClause : ASSIGN TO? (DISK | DISPLAY | KEYBOARD | PORT | PRINTER | READER | REMOTE | TAPE | VIRTUAL | (DYNAMIC | EXTERNAL)? assignmentName | literal) ; reserveClause : RESERVE (NO | integerLiteral) ALTERNATE? (AREA | AREAS)? ; organizationClause : (ORGANIZATION IS?)? (LINE | RECORD BINARY | RECORD | BINARY)? (SEQUENTIAL | RELATIVE | INDEXED) ; paddingCharacterClause : PADDING CHARACTER? IS? (qualifiedDataName | literal) ; recordDelimiterClause : RECORD DELIMITER IS? (STANDARD_1 | IMPLICIT | assignmentName) ; accessModeClause : ACCESS MODE? IS? (SEQUENTIAL | RANDOM | DYNAMIC | EXCLUSIVE) ; recordKeyClause : RECORD KEY? IS? qualifiedDataName passwordClause? (WITH? DUPLICATES)? ; alternateRecordKeyClause : ALTERNATE RECORD KEY? IS? qualifiedDataName passwordClause? (WITH? DUPLICATES)? ; passwordClause : PASSWORD IS? dataName ; fileStatusClause : FILE? STATUS IS? qualifiedDataName qualifiedDataName? ; relativeKeyClause : RELATIVE KEY? IS? qualifiedDataName ; // - io control paragraph ---------------------------------- ioControlParagraph : I_O_CONTROL DOT_FS (fileName DOT_FS)? (ioControlClause* DOT_FS)? ; ioControlClause : rerunClause | sameClause | multipleFileClause | commitmentControlClause | applyWriteOnlyClause ; rerunClause : RERUN (ON (assignmentName | fileName))? EVERY (rerunEveryRecords | rerunEveryOf | rerunEveryClock) ; rerunEveryRecords : integerLiteral RECORDS ; rerunEveryOf : END? OF? (REEL | UNIT) OF fileName ; rerunEveryClock : integerLiteral CLOCK_UNITS? ; sameClause : SAME (RECORD | SORT | SORT_MERGE)? AREA? FOR? fileName+ ; multipleFileClause : MULTIPLE FILE TAPE? CONTAINS? multipleFilePosition+ ; multipleFilePosition : fileName (POSITION integerLiteral)? ; applyWriteOnlyClause : APPLY WRITE_ONLY (ON)? fileName+ ; commitmentControlClause : COMMITMENT CONTROL FOR? fileName ; // --- data division -------------------------------------------------------------------- dataDivision : DATA DIVISION DOT_FS dataDivisionSection* ; dataDivisionSection : fileSection | dataBaseSection | workingStorageSection | linkageSection | communicationSection | localStorageSection | screenSection | reportSection | programLibrarySection ; // -- file section ---------------------------------- fileSection : FILE SECTION DOT_FS fileDescriptionEntry* ; fileDescriptionEntry : (FD | SD) fileName (DOT_FS? fileDescriptionEntryClause)* DOT_FS dataDescriptionEntry* ; fileDescriptionEntryClause : externalClause | globalClause | blockContainsClause | recordContainsClause | labelRecordsClause | valueOfClause | dataRecordsClause | linageClause | codeSetClause | reportClause | recordingModeClause ; externalClause : IS? EXTERNAL ; globalClause : IS? GLOBAL ; blockContainsClause : BLOCK CONTAINS? integerLiteral blockContainsTo? (RECORDS | CHARACTERS)? ; blockContainsTo : TO integerLiteral ; recordContainsClause : RECORD (recordContainsClauseFormat1 | recordContainsClauseFormat2 | recordContainsClauseFormat3) ; recordContainsClauseFormat1 : CONTAINS? integerLiteral CHARACTERS? ; recordContainsClauseFormat2 : IS? VARYING IN? SIZE? (FROM? integerLiteral recordContainsTo? CHARACTERS?)? (DEPENDING ON? qualifiedDataName)? ; recordContainsClauseFormat3 : CONTAINS? integerLiteral recordContainsTo CHARACTERS? ; recordContainsTo : TO integerLiteral ; labelRecordsClause : LABEL (RECORD IS? | RECORDS ARE?) (OMITTED | STANDARD | dataName+) ; valueOfClause : VALUE OF valuePair+ ; valuePair : systemName IS? (qualifiedDataName | literal) ; dataRecordsClause : DATA (RECORD IS? | RECORDS ARE?) dataName+ ; linageClause : LINAGE IS? (dataName | integerLiteral) LINES? linageAt* ; linageAt : linageFootingAt | linageLinesAtTop | linageLinesAtBottom ; linageFootingAt : WITH? FOOTING AT? (dataName | integerLiteral) ; linageLinesAtTop : LINES? AT? TOP (dataName | integerLiteral) ; linageLinesAtBottom : LINES? AT? BOTTOM (dataName | integerLiteral) ; recordingModeClause : RECORDING MODE? IS? modeStatement ; modeStatement : cobolWord ; codeSetClause : CODE_SET IS? alphabetName ; reportClause : (REPORT IS? | REPORTS ARE?) reportName+ ; // -- data base section ---------------------------------- dataBaseSection : DATA_BASE SECTION DOT_FS dataBaseSectionEntry* ; dataBaseSectionEntry : integerLiteral literal INVOKE literal ; // -- working storage section ---------------------------------- workingStorageSection : WORKING_STORAGE SECTION DOT_FS dataDescriptionEntry* ; // -- linkage section ---------------------------------- linkageSection : LINKAGE SECTION DOT_FS dataDescriptionEntry* ; // -- communication section ---------------------------------- communicationSection : COMMUNICATION SECTION DOT_FS (communicationDescriptionEntry | dataDescriptionEntry)* ; communicationDescriptionEntry : communicationDescriptionEntryFormat1 | communicationDescriptionEntryFormat2 | communicationDescriptionEntryFormat3 ; communicationDescriptionEntryFormat1 : CD cdName FOR? INITIAL? INPUT ((symbolicQueueClause | symbolicSubQueueClause | messageDateClause | messageTimeClause | symbolicSourceClause | textLengthClause | endKeyClause | statusKeyClause | messageCountClause) | dataDescName)* DOT_FS ; communicationDescriptionEntryFormat2 : CD cdName FOR? OUTPUT (destinationCountClause | textLengthClause | statusKeyClause | destinationTableClause | errorKeyClause | symbolicDestinationClause)* DOT_FS ; communicationDescriptionEntryFormat3 : CD cdName FOR? INITIAL I_O ((messageDateClause | messageTimeClause | symbolicTerminalClause | textLengthClause | endKeyClause | statusKeyClause) | dataDescName)* DOT_FS ; destinationCountClause : DESTINATION COUNT IS? dataDescName ; destinationTableClause : DESTINATION TABLE OCCURS integerLiteral TIMES (INDEXED BY indexName+)? ; endKeyClause : END KEY IS? dataDescName ; errorKeyClause : ERROR KEY IS? dataDescName ; messageCountClause : MESSAGE? COUNT IS? dataDescName ; messageDateClause : MESSAGE DATE IS? dataDescName ; messageTimeClause : MESSAGE TIME IS? dataDescName ; statusKeyClause : STATUS KEY IS? dataDescName ; symbolicDestinationClause : SYMBOLIC? DESTINATION IS? dataDescName ; symbolicQueueClause : SYMBOLIC? QUEUE IS? dataDescName ; symbolicSourceClause : SYMBOLIC? SOURCE IS? dataDescName ; symbolicTerminalClause : SYMBOLIC? TERMINAL IS? dataDescName ; symbolicSubQueueClause : SYMBOLIC? (SUB_QUEUE_1 | SUB_QUEUE_2 | SUB_QUEUE_3) IS? dataDescName ; textLengthClause : TEXT LENGTH IS? dataDescName ; // -- local storage section ---------------------------------- localStorageSection : LOCAL_STORAGE SECTION DOT_FS (LD localName DOT_FS)? dataDescriptionEntry* ; // -- screen section ---------------------------------- screenSection : SCREEN SECTION DOT_FS screenDescriptionEntry* ; screenDescriptionEntry : INTEGERLITERAL (FILLER | screenName)? (screenDescriptionBlankClause | screenDescriptionBellClause | screenDescriptionBlinkClause | screenDescriptionEraseClause | screenDescriptionLightClause | screenDescriptionGridClause | screenDescriptionReverseVideoClause | screenDescriptionUnderlineClause | screenDescriptionSizeClause | screenDescriptionLineClause | screenDescriptionColumnClause | screenDescriptionForegroundColorClause | screenDescriptionBackgroundColorClause | screenDescriptionControlClause | screenDescriptionValueClause | screenDescriptionPictureClause | (screenDescriptionFromClause | screenDescriptionUsingClause) | screenDescriptionUsageClause | screenDescriptionBlankWhenZeroClause | screenDescriptionJustifiedClause | screenDescriptionSignClause | screenDescriptionAutoClause | screenDescriptionSecureClause | screenDescriptionRequiredClause | screenDescriptionPromptClause | screenDescriptionFullClause | screenDescriptionZeroFillClause)* DOT_FS ; screenDescriptionBlankClause : BLANK (SCREEN | LINE) ; screenDescriptionBellClause : BELL | BEEP ; screenDescriptionBlinkClause : BLINK ; screenDescriptionEraseClause : ERASE (EOL | EOS) ; screenDescriptionLightClause : HIGHLIGHT | LOWLIGHT ; screenDescriptionGridClause : GRID | LEFTLINE | OVERLINE ; screenDescriptionReverseVideoClause : REVERSE_VIDEO ; screenDescriptionUnderlineClause : UNDERLINE ; screenDescriptionSizeClause : SIZE IS? (integerLiteral | generalIdentifier) ; screenDescriptionLineClause : LINE (NUMBER? IS? (PLUS | PLUSCHAR | MINUSCHAR))? (integerLiteral | generalIdentifier) ; screenDescriptionColumnClause : (COLUMN | COL) (NUMBER? IS? (PLUS | PLUSCHAR | MINUSCHAR))? (integerLiteral | generalIdentifier) ; screenDescriptionForegroundColorClause : (FOREGROUND_COLOR | FOREGROUND_COLOUR) IS? (integerLiteral | generalIdentifier) ; screenDescriptionBackgroundColorClause : (BACKGROUND_COLOR | BACKGROUND_COLOUR) IS? (integerLiteral | generalIdentifier) ; screenDescriptionControlClause : CONTROL IS? generalIdentifier ; screenDescriptionValueClause : (VALUE IS?) literal ; screenDescriptionPictureClause : (PICTURE | PIC) IS2? pictureString ; screenDescriptionFromClause : FROM (literal | generalIdentifier) screenDescriptionToClause? ; screenDescriptionToClause : TO generalIdentifier ; screenDescriptionUsingClause : USING generalIdentifier ; screenDescriptionUsageClause : (USAGE IS?) (DISPLAY | DISPLAY_1) ; screenDescriptionBlankWhenZeroClause : BLANK WHEN? ZERO ; screenDescriptionJustifiedClause : (JUSTIFIED | JUST) RIGHT? ; screenDescriptionSignClause : (SIGN IS?)? (LEADING | TRAILING) (SEPARATE CHARACTER?)? ; screenDescriptionAutoClause : AUTO | AUTO_SKIP ; screenDescriptionSecureClause : SECURE | NO_ECHO ; screenDescriptionRequiredClause : REQUIRED | EMPTY_CHECK ; screenDescriptionPromptClause : PROMPT CHARACTER? IS? (literal | generalIdentifier) screenDescriptionPromptOccursClause? ; screenDescriptionPromptOccursClause : OCCURS integerLiteral TIMES? ; screenDescriptionFullClause : FULL | LENGTH_CHECK ; screenDescriptionZeroFillClause : ZERO_FILL ; // -- report section ---------------------------------- reportSection : REPORT SECTION DOT_FS reportDescription* ; reportDescription : reportDescriptionEntry reportGroupDescriptionEntry+ ; reportDescriptionEntry : RD reportName reportDescriptionGlobalClause? (reportDescriptionPageLimitClause reportDescriptionHeadingClause? reportDescriptionFirstDetailClause? reportDescriptionLastDetailClause? reportDescriptionFootingClause?)? DOT_FS ; reportDescriptionGlobalClause : IS? GLOBAL ; reportDescriptionPageLimitClause : PAGE (LIMIT IS? | LIMITS ARE?)? integerLiteral (LINE | LINES)? ; reportDescriptionHeadingClause : HEADING integerLiteral ; reportDescriptionFirstDetailClause : FIRST DETAIL integerLiteral ; reportDescriptionLastDetailClause : LAST DETAIL integerLiteral ; reportDescriptionFootingClause : FOOTING integerLiteral ; reportGroupDescriptionEntry : reportGroupDescriptionEntryFormat1 | reportGroupDescriptionEntryFormat2 | reportGroupDescriptionEntryFormat3 ; reportGroupDescriptionEntryFormat1 : integerLiteral dataName reportGroupLineNumberClause? reportGroupNextGroupClause? reportGroupTypeClause reportGroupUsageClause? DOT_FS ; reportGroupDescriptionEntryFormat2 : integerLiteral dataName? reportGroupLineNumberClause? reportGroupUsageClause DOT_FS ; reportGroupDescriptionEntryFormat3 : integerLiteral dataName? (reportGroupPictureClause | reportGroupUsageClause | reportGroupSignClause | reportGroupJustifiedClause | reportGroupBlankWhenZeroClause | reportGroupLineNumberClause | reportGroupColumnNumberClause | (reportGroupSourceClause | reportGroupValueClause | reportGroupSumClause | reportGroupResetClause) | reportGroupIndicateClause)* DOT_FS ; reportGroupBlankWhenZeroClause : BLANK WHEN? ZERO ; reportGroupColumnNumberClause : COLUMN NUMBER? IS? integerLiteral ; reportGroupIndicateClause : GROUP INDICATE? ; reportGroupJustifiedClause : (JUSTIFIED | JUST) RIGHT? ; reportGroupLineNumberClause : LINE? NUMBER? IS? (reportGroupLineNumberNextPage | reportGroupLineNumberPlus) ; reportGroupLineNumberNextPage : integerLiteral (ON? NEXT PAGE)? ; reportGroupLineNumberPlus : PLUS integerLiteral ; reportGroupNextGroupClause : NEXT GROUP IS? (integerLiteral | reportGroupNextGroupNextPage | reportGroupNextGroupPlus) ; reportGroupNextGroupPlus : PLUS integerLiteral ; reportGroupNextGroupNextPage : NEXT PAGE ; reportGroupPictureClause : (PICTURE | PIC) IS2? pictureString ; reportGroupResetClause : RESET ON? (FINAL | dataName) ; reportGroupSignClause : SIGN IS? (LEADING | TRAILING) SEPARATE CHARACTER? ; reportGroupSourceClause : SOURCE IS? generalIdentifier ; reportGroupSumClause : SUM generalIdentifier (COMMACHAR? generalIdentifier)* (UPON dataName (COMMACHAR? dataName)*)? ; reportGroupTypeClause : TYPE IS? (reportGroupTypeReportHeading | reportGroupTypePageHeading | reportGroupTypeControlHeading | reportGroupTypeDetail | reportGroupTypeControlFooting | reportGroupTypePageFooting | reportGroupTypeReportFooting) ; reportGroupTypeReportHeading : REPORT HEADING | RH ; reportGroupTypePageHeading : PAGE HEADING | PH ; reportGroupTypeControlHeading : (CONTROL HEADING | CH) (FINAL | dataName) ; reportGroupTypeDetail : DETAIL | DE ; reportGroupTypeControlFooting : (CONTROL FOOTING | CF) (FINAL | dataName) ; reportGroupUsageClause : (USAGE IS?)? (DISPLAY | DISPLAY_1) ; reportGroupTypePageFooting : PAGE FOOTING | PF ; reportGroupTypeReportFooting : REPORT FOOTING | RF ; reportGroupValueClause : VALUE IS? literal ; // -- program library section ---------------------------------- programLibrarySection : PROGRAM_LIBRARY SECTION DOT_FS libraryDescriptionEntry* ; libraryDescriptionEntry : libraryDescriptionEntryFormat1 | libraryDescriptionEntryFormat2 ; libraryDescriptionEntryFormat1 : LD libraryName EXPORT libraryAttributeClauseFormat1? libraryEntryProcedureClauseFormat1? ; libraryDescriptionEntryFormat2 : LB libraryName IMPORT libraryIsGlobalClause? libraryIsCommonClause? (libraryAttributeClauseFormat2 | libraryEntryProcedureClauseFormat2)* ; libraryAttributeClauseFormat1 : ATTRIBUTE (SHARING IS? (DONTCARE | PRIVATE | SHAREDBYRUNUNIT | SHAREDBYALL))? ; libraryAttributeClauseFormat2 : ATTRIBUTE libraryAttributeFunction? (LIBACCESS IS? (BYFUNCTION | BYTITLE))? libraryAttributeParameter? libraryAttributeTitle? ; libraryAttributeFunction : FUNCTIONNAME IS literal ; libraryAttributeParameter : LIBPARAMETER IS? literal ; libraryAttributeTitle : TITLE IS? literal ; libraryEntryProcedureClauseFormat1 : ENTRY_PROCEDURE programName libraryEntryProcedureForClause? ; libraryEntryProcedureClauseFormat2 : ENTRY_PROCEDURE programName libraryEntryProcedureForClause? libraryEntryProcedureWithClause? libraryEntryProcedureUsingClause? libraryEntryProcedureGivingClause? ; libraryEntryProcedureForClause : FOR literal ; libraryEntryProcedureGivingClause : GIVING dataName ; libraryEntryProcedureUsingClause : USING libraryEntryProcedureUsingName+ ; libraryEntryProcedureUsingName : dataName | fileName ; libraryEntryProcedureWithClause : WITH libraryEntryProcedureWithName+ ; libraryEntryProcedureWithName : localName | fileName ; libraryIsCommonClause : IS? COMMON ; libraryIsGlobalClause : IS? GLOBAL ; dataDescriptionEntry : dataDescriptionEntryFormat1 | dataDescriptionEntryFormat2 | dataDescriptionEntryFormat3 | dataDescriptionEntryExecSql ; dataDescriptionEntryFormat1 : otherLevel (FILLER | dataName1)? (dataGroupUsageClause | dataRedefinesClause | dataIntegerStringClause | dataExternalClause | dataGlobalClause | dataTypeDefClause | dataThreadLocalClause | dataPictureClause | dataCommonOwnLocalClause | dataTypeClause | dataUsingClause | dataUsageClause | dataValueClause | dataReceivedByClause | dataOccursClause | dataSignClause | dataSynchronizedClause | dataJustifiedClause | dataBlankWhenZeroClause | dataWithLowerBoundsClause | dataAlignedClause | dataRecordAreaClause)* (DOT_FS|DOT_FS2) ; dataDescriptionEntryFormat2 : LEVEL_NUMBER_66 dataName1 dataRenamesClause DOT_FS ; dataDescriptionEntryFormat3 : LEVEL_NUMBER_88 dataName1 dataValueClause DOT_FS ; dataDescriptionEntryExecSql : execSqlStatement+ ; dataGroupUsageClause : GROUP_USAGE IS? NATIONAL ; dataAlignedClause : ALIGNED ; dataBlankWhenZeroClause : BLANK WHEN? (ZERO | ZEROS | ZEROES) ; dataCommonOwnLocalClause : COMMON | OWN | LOCAL ; dataExternalClause : IS? EXTERNAL (BY literal)? ; dataGlobalClause : IS? GLOBAL ; dataIntegerStringClause : INTEGER | STRING ; dataJustifiedClause : (JUSTIFIED | JUST) RIGHT? ; dataOccursClause : OCCURS integerLiteral dataOccursTo? TIMES? (DEPENDING ON? qualifiedDataName)? dataOccursSort* (INDEXED BY? LOCAL? indexName+)? ; dataOccursTo : TO integerLiteral ; dataOccursSort : (ASCENDING | DESCENDING) KEY? IS? qualifiedDataName+ ; dataPictureClause : (PICTURE | PIC) IS2? pictureString+ ; pictureString : charString ; dataReceivedByClause : RECEIVED? BY? (CONTENT | REFERENCE | REF) ; dataRecordAreaClause : RECORD AREA ; dataRedefinesClause : REDEFINES dataName ; dataRenamesClause : RENAMES qualifiedDataName ((THROUGH | THRU) qualifiedDataName)? ; dataSignClause : (SIGN IS?)? (LEADING | TRAILING) (SEPARATE CHARACTER?)? ; dataSynchronizedClause : (SYNCHRONIZED | SYNC) (LEFT | RIGHT)? ; dataThreadLocalClause : IS? THREAD_LOCAL ; dataTypeClause : TYPE IS? (SHORT_DATE | LONG_DATE | NUMERIC_DATE | NUMERIC_TIME | LONG_TIME | (CLOB | BLOB | DBCLOB) LPARENCHAR integerLiteral RPARENCHAR) ; dataTypeDefClause : IS? TYPEDEF ; dataUsageClause : (USAGE IS?)? (BINARY (TRUNCATED | EXTENDED)? | BIT | COMP | COMP_1 | COMP_2 | COMP_3 | COMP_4 | COMP_5 | COMPUTATIONAL | COMPUTATIONAL_1 | COMPUTATIONAL_2 | COMPUTATIONAL_3 | COMPUTATIONAL_4 | COMPUTATIONAL_5 | CONTROL_POINT | DATE | DISPLAY | DISPLAY_1 | DOUBLE | EVENT | FUNCTION_POINTER | INDEX | KANJI | LOCK | NATIONAL | PACKED_DECIMAL | POINTER | PROCEDURE_POINTER | REAL | SQL | TASK) ; dataUsingClause : USING (LANGUAGE | CONVENTION) OF? (cobolWord | dataName) ; dataValueClause : ((VALUE | VALUES) (IS | ARE)?) dataValueInterval (COMMACHAR? dataValueInterval)* ; dataValueInterval : dataValueIntervalFrom dataValueIntervalTo? ; dataValueIntervalFrom : literal | cobolWord ; dataValueIntervalTo : (THROUGH | THRU) literal ; dataWithLowerBoundsClause : WITH? LOWER BOUNDS ; // --- procedure division -------------------------------------------------------------------- procedureDivision : PROCEDURE DIVISION procedureDivisionUsingClause? procedureDivisionGivingClause? DOT_FS procedureDeclaratives? procedureDivisionBody ; procedureDivisionUsingClause : (USING | CHAINING) procedureDivisionUsingParameter+ ; procedureDivisionGivingClause : (GIVING | RETURNING) dataName ; procedureDivisionUsingParameter : procedureDivisionByReferencePhrase | procedureDivisionByValuePhrase ; procedureDivisionByReferencePhrase : (BY? REFERENCE)? procedureDivisionByReference+ ; procedureDivisionByReference : (OPTIONAL? (fileName | generalIdentifier)) | ANY ; procedureDivisionByValuePhrase : BY? VALUE procedureDivisionByValue+ ; procedureDivisionByValue : literal | generalIdentifier | ANY ; procedureDeclaratives : DECLARATIVES DOT_FS procedureDeclarative+ END DECLARATIVES DOT_FS ; procedureDeclarative : procedureSectionHeader DOT_FS useStatement DOT_FS paragraphs ; procedureSectionHeader : sectionName SECTION integerLiteral? ; procedureDivisionBody : paragraphs procedureSection* ; // -- procedure section ---------------------------------- procedureSection : procedureSectionHeader DOT_FS paragraphs ; paragraphs : sentence* paragraph* ; paragraph : paragraphName DOT_FS (alteredGoTo | sentence*) ; sentence : (statement* DOT_FS) | skipStatement+ ; statement : acceptStatement | addStatement | alterStatement | callStatement | cancelStatement | closeStatement | computeStatement | continueStatement | deleteStatement | disableStatement | displayStatement | divideStatement | enableStatement | entryStatement | evaluateStatement | exhibitStatement | execCicsStatement | execSqlStatement | execSqlImsStatement | exitStatement | generateStatement | gobackStatement | goToStatement | ifStatement | initializeStatement | initiateStatement | inspectStatement | mergeStatement | moveStatement | multiplyStatement | openStatement | performStatement | purgeStatement | readStatement | receiveStatement | releaseStatement | returnStatement | rewriteStatement | searchStatement | sendStatement | serviceReloadStatement | serviceLabelStatement | setStatement | sortStatement | startStatement | stopStatement | stringStatement | subtractStatement | terminateStatement | titleStatement | unstringStatement | writeStatement | xmlStatement ; // accept statement acceptStatement : ACCEPT generalIdentifier (acceptFromDateStatement | acceptFromEscapeKeyStatement | acceptFromMnemonicStatement | acceptMessageCountStatement)? onExceptionClause? notOnExceptionClause? END_ACCEPT? ; acceptFromDateStatement : FROM (DATE YYYYMMDD? | DAY YYYYDDD? | DAY_OF_WEEK | TIME | TIMER | TODAYS_DATE MMDDYYYY? | TODAYS_NAME | YEAR | YYYYMMDD | YYYYDDD) ; acceptFromMnemonicStatement : FROM mnemonicName ; acceptFromEscapeKeyStatement : FROM ESCAPE KEY ; acceptMessageCountStatement : MESSAGE? COUNT ; // add statement addStatement : ADD (addToStatement | addToGivingStatement | addCorrespondingStatement) onSizeErrorPhrase? notOnSizeErrorPhrase? END_ADD? ; addToStatement : addFrom+ TO addTo+ ; addToGivingStatement : addFrom+ (TO addToGiving+)? GIVING addGiving+ ; addCorrespondingStatement : (CORRESPONDING | CORR) generalIdentifier TO addTo ; addFrom : literal | generalIdentifier ; addTo : generalIdentifier ROUNDED? ; addToGiving : literal | generalIdentifier ; addGiving : generalIdentifier ROUNDED? ; // altered go to statement alteredGoTo : GO TO? DOT_FS ; // alter statement alterStatement : ALTER alterProceedTo+ ; alterProceedTo : procedureName TO (PROCEED TO)? procedureName ; // call statement callStatement : CALL (generalIdentifier | literal) callUsingPhrase? callGivingPhrase? onOverflowPhrase? onExceptionClause? notOnExceptionClause? END_CALL? ; callUsingPhrase : USING callUsingParameter+ ; callUsingParameter : callByReferencePhrase | callByValuePhrase | callByContentPhrase ; callByReferencePhrase : (BY? REFERENCE)? callByReference+ ; callByReference : ((ADDRESS OF | INTEGER | STRING)? literal | fileName | generalIdentifier) | OMITTED ; callByValuePhrase : BY? VALUE callByValue+ ; callByValue : (ADDRESS OF | LENGTH OF?)? (literal | generalIdentifier) ; callByContentPhrase : BY? CONTENT callByContent+ ; callByContent : (ADDRESS OF | LENGTH OF?)? literal | generalIdentifier | OMITTED ; callGivingPhrase : (GIVING | RETURNING) generalIdentifier ; // cancel statement cancelStatement : CANCEL cancelCall+ ; cancelCall : libraryName (BYTITLE | BYFUNCTION) | literal | generalIdentifier ; // close statement closeStatement : CLOSE closeFile+ ; closeFile : fileName (closeReelUnitStatement | closeRelativeStatement | closePortFileIOStatement)? ; closeReelUnitStatement : (REEL | UNIT) (FOR? REMOVAL)? (WITH? (NO REWIND | LOCK))? ; closeRelativeStatement : WITH? (NO REWIND | LOCK) ; closePortFileIOStatement : (WITH? NO WAIT | WITH WAIT) (USING closePortFileIOUsing+)? ; closePortFileIOUsing : closePortFileIOUsingCloseDisposition | closePortFileIOUsingAssociatedData | closePortFileIOUsingAssociatedDataLength ; closePortFileIOUsingCloseDisposition : CLOSE_DISPOSITION OF? (ABORT | ORDERLY) ; closePortFileIOUsingAssociatedData : ASSOCIATED_DATA (integerLiteral | generalIdentifier) ; closePortFileIOUsingAssociatedDataLength : ASSOCIATED_DATA_LENGTH OF? (integerLiteral | generalIdentifier) ; // compute statement computeStatement : COMPUTE computeStore+ (EQUALCHAR | EQUAL) arithmeticExpression onSizeErrorPhrase? notOnSizeErrorPhrase? END_COMPUTE? ; computeStore : generalIdentifier ROUNDED? ; // continue statement continueStatement : CONTINUE ; // delete statement deleteStatement : DELETE fileName RECORD? invalidKeyPhrase? notInvalidKeyPhrase? END_DELETE? ; // disable statement disableStatement : DISABLE (INPUT TERMINAL? | I_O TERMINAL | OUTPUT) cdName WITH? KEY (literal | generalIdentifier) ; // display statement displayStatement : DISPLAY displayOperand+ displayAt? displayUpon? displayWith? ; displayOperand : literal | generalIdentifier ; displayAt : AT (literal | generalIdentifier) ; displayUpon : UPON (mnemonicName | environmentName) ; displayWith : WITH? NO ADVANCING ; // divide statement divideStatement : DIVIDE (literal | generalIdentifier) (divideIntoStatement | divideIntoGivingStatement | divideByGivingStatement) divideRemainder? onSizeErrorPhrase? notOnSizeErrorPhrase? END_DIVIDE? ; divideIntoStatement : INTO divideInto+ ; divideIntoGivingStatement : INTO (literal | generalIdentifier) divideGivingPhrase? ; divideByGivingStatement : BY (literal | generalIdentifier) divideGivingPhrase? ; divideGivingPhrase : GIVING divideGiving+ ; divideInto : generalIdentifier ROUNDED? ; divideGiving : generalIdentifier ROUNDED? ; divideRemainder : REMAINDER generalIdentifier ; // enable statement enableStatement : ENABLE (INPUT TERMINAL? | I_O TERMINAL | OUTPUT) cdName WITH? KEY (literal | generalIdentifier) ; // entry statement entryStatement : ENTRY literal (USING generalIdentifier+)? ; // evaluate statement evaluateStatement : EVALUATE evaluateSelect evaluateAlsoSelect* evaluateWhenPhrase+ evaluateWhenOther? END_EVALUATE? ; evaluateSelect : literal | arithmeticExpression | condition | generalIdentifier ; evaluateAlsoSelect : ALSO evaluateSelect ; evaluateWhenPhrase : evaluateWhen+ statement* ; evaluateWhen : WHEN evaluateCondition evaluateAlsoCondition* ; evaluateCondition : ANY | NOT? evaluateValue evaluateThrough? | condition | booleanLiteral ; evaluateThrough : (THROUGH | THRU) evaluateValue ; evaluateAlsoCondition : ALSO evaluateCondition ; evaluateWhenOther : WHEN OTHER statement* ; evaluateValue : literal | arithmeticExpression | generalIdentifier ; // exec cics statement execCicsStatement : EXEC CICS allRules END_EXEC DOT_FS? ; // exec sql statement execSqlStatement : EXEC SQL ~END_EXEC*? END_EXEC DOT_FS? ; // exec sql ims statement execSqlImsStatement : EXEC SQLIMS ~END_EXEC*? END_EXEC DOT_FS? ; // exhibit statement exhibitStatement : EXHIBIT NAMED? CHANGED? exhibitOperand+ ; exhibitOperand : literal | generalIdentifier ; // exit statement exitStatement : EXIT PROGRAM? ; // generate statement generateStatement : GENERATE reportName ; // goback statement gobackStatement : GOBACK ; // goto statement goToStatement : GO TO? (goToStatementSimple | goToDependingOnStatement) ; goToStatementSimple : procedureName ; goToDependingOnStatement : procedureName+ (DEPENDING ON? generalIdentifier)? | MORE_LABELS ; // if statement ifStatement : IF condition ifThen ifElse? END_IF? ; ifThen : THEN? (NEXT SENTENCE | statement+?) ; ifElse : ELSE (NEXT SENTENCE | statement+?) ; // initialize statement initializeStatement : INITIALIZE generalIdentifier+ initializeReplacingPhrase? ; initializeReplacingPhrase : REPLACING initializeReplacingBy+ ; initializeReplacingBy : (ALPHABETIC | ALPHANUMERIC | ALPHANUMERIC_EDITED | NATIONAL | NATIONAL_EDITED | NUMERIC | NUMERIC_EDITED | DBCS | EGCS) DATA? BY (literal | generalIdentifier) ; // initiate statement initiateStatement : INITIATE reportName+ ; // inspect statement inspectStatement : INSPECT generalIdentifier (inspectTallyingPhrase | inspectReplacingPhrase | inspectTallyingReplacingPhrase | inspectConvertingPhrase) ; inspectTallyingPhrase : TALLYING inspectFor+ ; inspectReplacingPhrase : REPLACING (inspectReplacingCharacters | inspectReplacingAllLeadings)+ ; inspectTallyingReplacingPhrase : TALLYING inspectFor+ inspectReplacingPhrase+ ; inspectConvertingPhrase : CONVERTING (literal | generalIdentifier) inspectTo inspectBeforeAfter* ; inspectFor : generalIdentifier FOR (inspectCharacters | inspectAllLeadings)+ ; inspectCharacters : CHARACTERS inspectBeforeAfter* ; inspectReplacingCharacters : CHARACTERS inspectBy inspectBeforeAfter* ; inspectAllLeadings : (ALL | LEADING) inspectAllLeading+ ; inspectReplacingAllLeadings : (ALL | LEADING | FIRST) inspectReplacingAllLeading+ ; inspectAllLeading : (literal | generalIdentifier) inspectBeforeAfter* ; inspectReplacingAllLeading : (literal | generalIdentifier) inspectBy inspectBeforeAfter* ; inspectBy : BY (literal | generalIdentifier) ; inspectTo : TO (literal | generalIdentifier) ; inspectBeforeAfter : (BEFORE | AFTER) INITIAL? (literal | generalIdentifier) ; // merge statement mergeStatement : MERGE fileName mergeOnKeyClause+ mergeCollatingSequencePhrase? mergeUsing* mergeOutputProcedurePhrase? mergeGivingPhrase* ; mergeOnKeyClause : ON? (ASCENDING | DESCENDING) KEY? qualifiedDataName+ ; mergeCollatingSequencePhrase : COLLATING? SEQUENCE IS? alphabetName+ mergeCollatingAlphanumeric? mergeCollatingNational? ; mergeCollatingAlphanumeric : FOR? ALPHANUMERIC IS alphabetName ; mergeCollatingNational : FOR? NATIONAL IS? alphabetName ; mergeUsing : USING fileName+ ; mergeOutputProcedurePhrase : OUTPUT PROCEDURE IS? procedureName mergeOutputThrough? ; mergeOutputThrough : (THROUGH | THRU) procedureName ; mergeGivingPhrase : GIVING mergeGiving+ ; mergeGiving : fileName (LOCK | SAVE | NO REWIND | CRUNCH | RELEASE | WITH REMOVE CRUNCH)? ; // move statement moveStatement : MOVE ALL? (moveToStatement | moveCorrespondingToStatement) ; moveToStatement : moveToSendingArea TO generalIdentifier+ ; moveToSendingArea : literal | generalIdentifier ; moveCorrespondingToStatement : (CORRESPONDING | CORR) moveCorrespondingToSendingArea TO generalIdentifier+ ; moveCorrespondingToSendingArea : generalIdentifier ; // multiply statement multiplyStatement : MULTIPLY (literal | generalIdentifier) BY (multiplyRegular | multiplyGiving) onSizeErrorPhrase? notOnSizeErrorPhrase? END_MULTIPLY? ; multiplyRegular : multiplyRegularOperand+ ; multiplyRegularOperand : generalIdentifier ROUNDED? ; multiplyGiving : multiplyGivingOperand GIVING multiplyGivingResult+ ; multiplyGivingOperand : literal | generalIdentifier ; multiplyGivingResult : generalIdentifier ROUNDED? ; // open statement openStatement : OPEN (openInputStatement | openOutputStatement | openIOStatement | openExtendStatement)+ ; openInputStatement : INPUT openInput+ ; openInput : fileName (REVERSED | WITH? NO REWIND)? ; openOutputStatement : OUTPUT openOutput+ ; openOutput : fileName (WITH? NO REWIND)? ; openIOStatement : I_O fileName+ ; openExtendStatement : EXTEND fileName+ ; // perform statement performStatement : PERFORM (performInlineStatement | performProcedureStatement) ; performInlineStatement : performType? statement* END_PERFORM ; performProcedureStatement : procedureName ((THROUGH | THRU) procedureName)? performType? ; performType : performTimes | performUntil | performVarying ; performTimes : (integerLiteral | generalIdentifier) TIMES ; performUntil : performTestClause? UNTIL condition ; performVarying : performTestClause performVaryingClause | performVaryingClause performTestClause? ; performVaryingClause : VARYING performVaryingPhrase performAfter* ; performVaryingPhrase : (literal | generalIdentifier) performFrom performBy performUntil ; performAfter : AFTER performVaryingPhrase ; performFrom : FROM (literal | generalIdentifier) ; performBy : BY (literal | generalIdentifier) ; performTestClause : WITH? TEST (BEFORE | AFTER) ; // purge statement purgeStatement : PURGE cdName+ ; // read statement readStatement : READ fileName NEXT? RECORD? readInto? readWith? readKey? invalidKeyPhrase? notInvalidKeyPhrase? atEndPhrase? notAtEndPhrase? END_READ? ; readInto : INTO generalIdentifier ; readWith : WITH? ((KEPT | NO) LOCK | WAIT) ; readKey : KEY IS? qualifiedDataName ; // receive statement receiveStatement : RECEIVE (receiveFromStatement | receiveIntoStatement) onExceptionClause? notOnExceptionClause? END_RECEIVE? ; receiveFromStatement : dataName FROM receiveFrom (receiveBefore | receiveWith | receiveThread | receiveSize | receiveStatus)* ; receiveFrom : THREAD dataName | LAST THREAD | ANY THREAD ; receiveIntoStatement : cdName (MESSAGE | SEGMENT) INTO? generalIdentifier receiveNoData? receiveWithData? ; receiveNoData : NO DATA statement* ; receiveWithData : WITH DATA statement* ; receiveBefore : BEFORE TIME? (numericLiteral | generalIdentifier) ; receiveWith : WITH? NO WAIT ; receiveThread : THREAD IN? dataName ; receiveSize : SIZE IN? (numericLiteral | generalIdentifier) ; receiveStatus : STATUS IN? (generalIdentifier) ; // release statement releaseStatement : RELEASE recordName (FROM qualifiedDataName)? ; // return statement returnStatement : RETURN fileName RECORD? returnInto? atEndPhrase notAtEndPhrase? END_RETURN? ; returnInto : INTO qualifiedDataName ; // rewrite statement rewriteStatement : REWRITE recordName rewriteFrom? invalidKeyPhrase? notInvalidKeyPhrase? END_REWRITE? ; rewriteFrom : FROM generalIdentifier ; // search statement searchStatement : SEARCH ALL? qualifiedDataName searchVarying? atEndPhrase? searchWhen+ END_SEARCH? ; searchVarying : VARYING qualifiedDataName ; searchWhen : WHEN condition (NEXT SENTENCE | statement*) ; // send statement sendStatement : SEND (sendStatementSync | sendStatementAsync) onExceptionClause? notOnExceptionClause? ; sendStatementSync : (literal | generalIdentifier) sendFromPhrase? sendWithPhrase? sendReplacingPhrase? sendAdvancingPhrase? ; sendStatementAsync : TO (TOP | BOTTOM) generalIdentifier ; sendFromPhrase : FROM generalIdentifier ; sendWithPhrase : WITH (EGI | EMI | ESI | generalIdentifier) ; sendReplacingPhrase : REPLACING LINE? ; sendAdvancingPhrase : (BEFORE | AFTER) ADVANCING? (sendAdvancingPage | sendAdvancingLines | sendAdvancingMnemonic) ; sendAdvancingPage : PAGE ; sendAdvancingLines : (literal | generalIdentifier) (LINE | LINES)? ; sendAdvancingMnemonic : mnemonicName ; // set statement setStatement : SET (setToStatement+ | setUpDownByStatement) ; setToStatement : setTo+ TO setToValue+ ; setUpDownByStatement : setTo+ (UP BY | DOWN BY) setByValue ; setTo : generalIdentifier ; setToValue : ON | OFF | ENTRY (literal | generalIdentifier) | literal | generalIdentifier ; setByValue : literal | generalIdentifier ; // service statement serviceLabelStatement : SERVICE LABEL ; serviceReloadStatement : SERVICE RELOAD generalIdentifier ; // skip statement skipStatement : SKIP1|SKIP2|SKIP3 DOT_FS? ; // sort statement sortStatement : SORT fileName sortOnKeyClause+ sortDuplicatesPhrase? sortCollatingSequencePhrase? sortInputProcedurePhrase? sortUsing* sortOutputProcedurePhrase? sortGivingPhrase* ; sortOnKeyClause : ON? (ASCENDING | DESCENDING) KEY? qualifiedDataName+ ; sortDuplicatesPhrase : WITH? DUPLICATES IN? ORDER? ; sortCollatingSequencePhrase : COLLATING? SEQUENCE IS? alphabetName+ sortCollatingAlphanumeric? sortCollatingNational? ; sortCollatingAlphanumeric : FOR? ALPHANUMERIC IS alphabetName ; sortCollatingNational : FOR? NATIONAL IS? alphabetName ; sortInputProcedurePhrase : INPUT PROCEDURE IS? procedureName sortInputThrough? ; sortInputThrough : (THROUGH | THRU) procedureName ; sortUsing : USING fileName+ ; sortOutputProcedurePhrase : OUTPUT PROCEDURE IS? procedureName sortOutputThrough? ; sortOutputThrough : (THROUGH | THRU) procedureName ; sortGivingPhrase : GIVING sortGiving+ ; sortGiving : fileName (LOCK | SAVE | NO REWIND | CRUNCH | RELEASE | WITH REMOVE CRUNCH)? ; // startPosition statement startStatement : START fileName startKey? invalidKeyPhrase? notInvalidKeyPhrase? END_START? ; startKey : KEY IS? (EQUAL TO? | EQUALCHAR | GREATER THAN? | MORETHANCHAR | NOT LESS THAN? | NOT LESSTHANCHAR | GREATER THAN? OR EQUAL TO? | MORETHANOREQUAL) qualifiedDataName ; // stopPosition statement stopStatement : STOP (RUN | literal | stopStatementGiving) ; stopStatementGiving : RUN (GIVING | RETURNING) (integerLiteral | generalIdentifier) ; // string statement stringStatement : STRING stringSendingPhrase+ stringIntoPhrase stringWithPointerPhrase? onOverflowPhrase? notOnOverflowPhrase? END_STRING? ; stringSendingPhrase : stringSending (COMMACHAR? stringSending)* (stringDelimitedByPhrase | stringForPhrase) ; stringSending : literal | generalIdentifier ; stringDelimitedByPhrase : DELIMITED BY? (SIZE | literal | generalIdentifier) ; stringForPhrase : FOR (literal | generalIdentifier) ; stringIntoPhrase : INTO generalIdentifier ; stringWithPointerPhrase : WITH? POINTER qualifiedDataName ; // subtract statement subtractStatement : SUBTRACT (subtractFromStatement | subtractFromGivingStatement | subtractCorrespondingStatement) onSizeErrorPhrase? notOnSizeErrorPhrase? END_SUBTRACT? ; subtractFromStatement : subtractSubtrahend+ FROM subtractMinuend+ ; subtractFromGivingStatement : subtractSubtrahend+ FROM subtractMinuendGiving GIVING subtractGiving+ ; subtractCorrespondingStatement : (CORRESPONDING | CORR) qualifiedDataName FROM subtractMinuendCorresponding ; subtractSubtrahend : literal | generalIdentifier ; subtractMinuend : generalIdentifier ROUNDED? ; subtractMinuendGiving : literal | generalIdentifier ; subtractGiving : generalIdentifier ROUNDED? ; subtractMinuendCorresponding : qualifiedDataName ROUNDED? ; // terminate statement terminateStatement : TERMINATE reportName ; // title statement titleStatement : TITLE literal DOT_FS? ; // unstring statement unstringStatement : UNSTRING unstringSendingPhrase unstringIntoPhrase unstringWithPointerPhrase? unstringTallyingPhrase? onOverflowPhrase? notOnOverflowPhrase? END_UNSTRING? ; unstringSendingPhrase : generalIdentifier (unstringDelimitedByPhrase unstringOrAllPhrase*)? ; unstringDelimitedByPhrase : DELIMITED BY? ALL? (literal | generalIdentifier) ; unstringOrAllPhrase : OR ALL? (literal | generalIdentifier) ; unstringIntoPhrase : INTO unstringInto+ ; unstringInto : generalIdentifier unstringDelimiterIn? unstringCountIn? ; unstringDelimiterIn : DELIMITER IN? generalIdentifier ; unstringCountIn : COUNT IN? generalIdentifier ; unstringWithPointerPhrase : WITH? POINTER qualifiedDataName ; unstringTallyingPhrase : TALLYING IN? qualifiedDataName ; // use statement useStatement : USE (useAfterClause | useDebugClause) ; useAfterClause : GLOBAL? AFTER STANDARD? (EXCEPTION | ERROR) PROCEDURE ON? useAfterOn ; useAfterOn : INPUT | OUTPUT | I_O | EXTEND | fileName+ ; useDebugClause : FOR? DEBUGGING ON? useDebugOn+ ; useDebugOn : ALL PROCEDURES | ALL REFERENCES? OF? generalIdentifier | procedureName | fileName ; // write statement writeStatement : WRITE recordName writeFromPhrase? writeAdvancingPhrase? writeAtEndOfPagePhrase? writeNotAtEndOfPagePhrase? invalidKeyPhrase? notInvalidKeyPhrase? END_WRITE? ; writeFromPhrase : FROM (literal | generalIdentifier) ; writeAdvancingPhrase : (BEFORE | AFTER) ADVANCING? (writeAdvancingPage | writeAdvancingLines | writeAdvancingMnemonic) ; writeAdvancingPage : PAGE ; writeAdvancingLines : (literal | generalIdentifier) (LINE | LINES)? ; writeAdvancingMnemonic : mnemonicName ; writeAtEndOfPagePhrase : AT? (END_OF_PAGE | EOP) statement* ; writeNotAtEndOfPagePhrase : NOT AT? (END_OF_PAGE | EOP) statement* ; // xml statement xmlStatement : XML PARSE generalIdentifier xmlEncoding? xmlNational? xmlValidating? xmlProcessinProcedure xmlThru? onExceptionClause? notOnExceptionClause? END_XML? ; xmlEncoding : WITH? ENCODING integerLiteral ; xmlNational : RETURNING NATIONAL ; xmlValidating : VALIDATING WITH? (generalIdentifier | FILE literal) ; xmlThru : (THROUGH | THRU) procedureName ; xmlProcessinProcedure : PROCESSING PROCEDURE IS? procedureName ; // statement phrases ---------------------------------- atEndPhrase : AT? END statement* ; notAtEndPhrase : NOT AT? END statement* ; invalidKeyPhrase : INVALID KEY? statement* ; notInvalidKeyPhrase : NOT INVALID KEY? statement* ; onOverflowPhrase : ON? OVERFLOW statement* ; notOnOverflowPhrase : NOT ON? OVERFLOW statement* ; onSizeErrorPhrase : ON? SIZE ERROR statement* ; notOnSizeErrorPhrase : NOT ON? SIZE ERROR statement* ; // statement clauses ---------------------------------- onExceptionClause : ON? EXCEPTION statement* ; notOnExceptionClause : NOT ON? EXCEPTION statement* ; // condition ---------------------------------- condition : combinableCondition andOrCondition* ; andOrCondition : (AND | OR) (combinableCondition | abbreviation+) ; combinableCondition : NOT? simpleCondition ; simpleCondition : LPARENCHAR condition RPARENCHAR | relationCondition | classCondition | conditionNameReference ; classCondition : generalIdentifier IS? NOT? (NUMERIC | ALPHABETIC | ALPHABETIC_LOWER | ALPHABETIC_UPPER | DBCS | KANJI | className) ; conditionNameReference : conditionName (inData* inFile? conditionNameSubscriptReference* | inMnemonic*) ; conditionNameSubscriptReference : LPARENCHAR subscript (COMMACHAR? subscript)* RPARENCHAR ; // relation ---------------------------------- relationCondition : relationSignCondition | relationArithmeticComparison | relationCombinedComparison ; relationSignCondition : arithmeticExpression IS? NOT? (POSITIVE | NEGATIVE | ZERO) ; relationArithmeticComparison : arithmeticExpression relationalOperator arithmeticExpression ; relationCombinedComparison : arithmeticExpression relationalOperator LPARENCHAR relationCombinedCondition RPARENCHAR ; relationCombinedCondition : arithmeticExpression ((AND | OR) arithmeticExpression)+ ; relationalOperator : (IS | ARE)? (NOT? (GREATER THAN? | MORETHANCHAR | LESS THAN? | LESSTHANCHAR | EQUAL TO? | EQUALCHAR) | NOTEQUALCHAR | GREATER THAN? OR EQUAL TO? | MORETHANOREQUAL | LESS THAN? OR EQUAL TO? | LESSTHANOREQUAL) ; abbreviation : NOT? relationalOperator? (arithmeticExpression | LPARENCHAR arithmeticExpression abbreviation RPARENCHAR) ; // comment entry commentEntry : COMMENTENTRYLINE+ ; ",12387,False,2490.0354220730137,median "/* * Licensed under the Apache License, Version 2.0 (the ""License""); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is an adaptation of Presto's presto-parser/src/main/antlr4/com/facebook/presto/sql/parser/SqlBase.g4 grammar. */ grammar SqlBase; @members { /** * When false, INTERSECT is given the greater precedence over the other set * operations (UNION, EXCEPT and MINUS) as per the SQL standard. */ public boolean legacy_setops_precedence_enbled = false; /** * Verify whether current token is a valid decimal token (which contains dot). * Returns true if the character that follows the token is not a digit or letter or underscore. * * For example: * For char stream ""2.3"", ""2."" is not a valid decimal token, because it is followed by digit '3'. * For char stream ""2.3_"", ""2.3"" is not a valid decimal token, because it is followed by '_'. * For char stream ""2.3W"", ""2.3"" is not a valid decimal token, because it is followed by 'W'. * For char stream ""12.0D 34.E2+0.12 "" 12.0D is a valid decimal token because it is followed * by a space. 34.E2 is a valid decimal token because it is followed by symbol '+' * which is not a digit or letter or underscore. */ public boolean isValidDecimal() { int nextChar = _input.LA(1); if (nextChar >= 'A' && nextChar <= 'Z' || nextChar >= '0' && nextChar <= '9' || nextChar == '_') { return false; } else { return true; } } /** * When true, ANSI SQL parsing mode is enabled. */ public boolean ansi = false; } singleStatement : statement EOF ; singleExpression : namedExpression EOF ; singleTableIdentifier : tableIdentifier EOF ; singleMultipartIdentifier : multipartIdentifier EOF ; singleFunctionIdentifier : functionIdentifier EOF ; singleDataType : dataType EOF ; singleTableSchema : colTypeList EOF ; singleInterval : INTERVAL? multiUnitsInterval EOF ; statement : query #statementDefault | ctes? dmlStatementNoWith #dmlStatement | USE NAMESPACE? multipartIdentifier #use | CREATE (database | NAMESPACE) (IF NOT EXISTS)? multipartIdentifier ((COMMENT comment=STRING) | locationSpec | (WITH (DBPROPERTIES | PROPERTIES) tablePropertyList))* #createNamespace | ALTER database db=errorCapturingIdentifier SET DBPROPERTIES tablePropertyList #setDatabaseProperties | ALTER database db=errorCapturingIdentifier SET locationSpec #setDatabaseLocation | DROP (database | NAMESPACE) (IF EXISTS)? multipartIdentifier (RESTRICT | CASCADE)? #dropNamespace | SHOW (DATABASES | NAMESPACES) ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showNamespaces | createTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createTable | createTableHeader ('(' columns=colTypeList ')')? ((COMMENT comment=STRING) | (PARTITIONED BY '(' partitionColumns=colTypeList ')' | PARTITIONED BY partitionColumnNames=identifierList) | bucketSpec | skewSpec | rowFormat | createFileFormat | locationSpec | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #createHiveTable | CREATE TABLE (IF NOT EXISTS)? target=tableIdentifier LIKE source=tableIdentifier tableProvider? locationSpec? #createTableLike | replaceTableHeader ('(' colTypeList ')')? tableProvider ((OPTIONS options=tablePropertyList) | (PARTITIONED BY partitioning=transformList) | bucketSpec | locationSpec | (COMMENT comment=STRING) | (TBLPROPERTIES tableProps=tablePropertyList))* (AS? query)? #replaceTable | ANALYZE TABLE multipartIdentifier partitionSpec? COMPUTE STATISTICS (identifier | FOR COLUMNS identifierSeq | FOR ALL COLUMNS)? #analyze | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) columns=qualifiedColTypeWithPositionList #addTableColumns | ALTER TABLE multipartIdentifier ADD (COLUMN | COLUMNS) '(' columns=qualifiedColTypeWithPositionList ')' #addTableColumns | ALTER TABLE table=multipartIdentifier RENAME COLUMN from=multipartIdentifier TO to=errorCapturingIdentifier #renameTableColumn | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) '(' columns=multipartIdentifierList ')' #dropTableColumns | ALTER TABLE multipartIdentifier DROP (COLUMN | COLUMNS) columns=multipartIdentifierList #dropTableColumns | ALTER (TABLE | VIEW) from=tableIdentifier RENAME TO to=tableIdentifier #renameTable | ALTER (TABLE | VIEW) multipartIdentifier SET TBLPROPERTIES tablePropertyList #setTableProperties | ALTER (TABLE | VIEW) multipartIdentifier UNSET TBLPROPERTIES (IF EXISTS)? tablePropertyList #unsetTableProperties | ALTER TABLE table=multipartIdentifier (ALTER | CHANGE) COLUMN? column=multipartIdentifier (TYPE dataType)? (COMMENT comment=STRING)? colPosition? #alterTableColumn | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDE STRING (WITH SERDEPROPERTIES tablePropertyList)? #setTableSerDe | ALTER TABLE multipartIdentifier (partitionSpec)? SET SERDEPROPERTIES tablePropertyList #setTableSerDe | ALTER (TABLE | VIEW) multipartIdentifier ADD (IF NOT EXISTS)? partitionSpecLocation+ #addTablePartition | ALTER TABLE multipartIdentifier from=partitionSpec RENAME TO to=partitionSpec #renameTablePartition | ALTER (TABLE | VIEW) multipartIdentifier DROP (IF EXISTS)? partitionSpec (',' partitionSpec)* PURGE? #dropTablePartitions | ALTER TABLE multipartIdentifier (partitionSpec)? SET locationSpec #setTableLocation | ALTER TABLE multipartIdentifier RECOVER PARTITIONS #recoverPartitions | DROP TABLE (IF EXISTS)? multipartIdentifier PURGE? #dropTable | DROP VIEW (IF EXISTS)? multipartIdentifier #dropView | CREATE (OR REPLACE)? (GLOBAL? TEMPORARY)? VIEW (IF NOT EXISTS)? tableIdentifier identifierCommentList? ((COMMENT STRING) | (PARTITIONED ON identifierList) | (TBLPROPERTIES tablePropertyList))* AS query #createView | CREATE (OR REPLACE)? GLOBAL? TEMPORARY VIEW tableIdentifier ('(' colTypeList ')')? tableProvider (OPTIONS tablePropertyList)? #createTempViewUsing | ALTER VIEW multipartIdentifier AS? query #alterViewQuery | CREATE (OR REPLACE)? TEMPORARY? FUNCTION (IF NOT EXISTS)? multipartIdentifier AS className=STRING (USING resource (',' resource)*)? #createFunction | DROP TEMPORARY? FUNCTION (IF EXISTS)? multipartIdentifier #dropFunction | EXPLAIN (LOGICAL | FORMATTED | EXTENDED | CODEGEN | COST)? statement #explain | SHOW TABLES ((FROM | IN) multipartIdentifier)? (LIKE? pattern=STRING)? #showTables | SHOW TABLE EXTENDED ((FROM | IN) db=errorCapturingIdentifier)? LIKE pattern=STRING partitionSpec? #showTable | SHOW TBLPROPERTIES table=tableIdentifier ('(' key=tablePropertyKey ')')? #showTblProperties | SHOW COLUMNS (FROM | IN) table=multipartIdentifier ((FROM | IN) namespace=multipartIdentifier)? #showColumns | SHOW PARTITIONS multipartIdentifier partitionSpec? #showPartitions | SHOW identifier? FUNCTIONS (LIKE? (multipartIdentifier | pattern=STRING))? #showFunctions | SHOW CREATE TABLE multipartIdentifier #showCreateTable | SHOW CURRENT NAMESPACE #showCurrentNamespace | (DESC | DESCRIBE) FUNCTION EXTENDED? describeFuncName #describeFunction | (DESC | DESCRIBE) database EXTENDED? db=errorCapturingIdentifier #describeDatabase | (DESC | DESCRIBE) TABLE? option=(EXTENDED | FORMATTED)? multipartIdentifier partitionSpec? describeColName? #describeTable | (DESC | DESCRIBE) QUERY? query #describeQuery | REFRESH TABLE multipartIdentifier #refreshTable | REFRESH (STRING | .*?) #refreshResource | CACHE LAZY? TABLE multipartIdentifier (OPTIONS options=tablePropertyList)? (AS? query)? #cacheTable | UNCACHE TABLE (IF EXISTS)? multipartIdentifier #uncacheTable | CLEAR CACHE #clearCache | LOAD DATA LOCAL? INPATH path=STRING OVERWRITE? INTO TABLE multipartIdentifier partitionSpec? #loadData | TRUNCATE TABLE multipartIdentifier partitionSpec? #truncateTable | MSCK REPAIR TABLE multipartIdentifier #repairTable | op=(ADD | LIST) identifier .*? #manageResource | SET ROLE .*? #failNativeCommand | SET .*? #setConfiguration | RESET #resetConfiguration | DELETE FROM multipartIdentifier tableAlias whereClause? #deleteFromTable | UPDATE multipartIdentifier tableAlias setClause whereClause? #updateTable | MERGE INTO target=multipartIdentifier targetAlias=tableAlias USING (source=multipartIdentifier | '(' sourceQuery=query')') sourceAlias=tableAlias ON mergeCondition=booleanExpression matchedClause* notMatchedClause* #mergeIntoTable | unsupportedHiveNativeCommands .*? #failNativeCommand ; unsupportedHiveNativeCommands : kw1=CREATE kw2=ROLE | kw1=DROP kw2=ROLE | kw1=GRANT kw2=ROLE? | kw1=REVOKE kw2=ROLE? | kw1=SHOW kw2=GRANT | kw1=SHOW kw2=ROLE kw3=GRANT? | kw1=SHOW kw2=PRINCIPALS | kw1=SHOW kw2=ROLES | kw1=SHOW kw2=CURRENT kw3=ROLES | kw1=EXPORT kw2=TABLE | kw1=IMPORT kw2=TABLE | kw1=SHOW kw2=COMPACTIONS | kw1=SHOW kw2=CREATE kw3=TABLE | kw1=SHOW kw2=TRANSACTIONS | kw1=SHOW kw2=INDEXES | kw1=SHOW kw2=LOCKS | kw1=CREATE kw2=INDEX | kw1=DROP kw2=INDEX | kw1=ALTER kw2=INDEX | kw1=LOCK kw2=TABLE | kw1=LOCK kw2=DATABASE | kw1=UNLOCK kw2=TABLE | kw1=UNLOCK kw2=DATABASE | kw1=CREATE kw2=TEMPORARY kw3=MACRO | kw1=DROP kw2=TEMPORARY kw3=MACRO | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=CLUSTERED | kw1=ALTER kw2=TABLE tableIdentifier kw3=CLUSTERED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SORTED | kw1=ALTER kw2=TABLE tableIdentifier kw3=SKEWED kw4=BY | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=SKEWED | kw1=ALTER kw2=TABLE tableIdentifier kw3=NOT kw4=STORED kw5=AS kw6=DIRECTORIES | kw1=ALTER kw2=TABLE tableIdentifier kw3=SET kw4=SKEWED kw5=LOCATION | kw1=ALTER kw2=TABLE tableIdentifier kw3=EXCHANGE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=ARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=UNARCHIVE kw4=PARTITION | kw1=ALTER kw2=TABLE tableIdentifier kw3=TOUCH | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=COMPACT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=CONCATENATE | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=SET kw4=FILEFORMAT | kw1=ALTER kw2=TABLE tableIdentifier partitionSpec? kw3=REPLACE kw4=COLUMNS | kw1=START kw2=TRANSACTION | kw1=COMMIT | kw1=ROLLBACK | kw1=DFS | kw1=DELETE kw2=FROM ; createTableHeader : CREATE TEMPORARY? EXTERNAL? TABLE (IF NOT EXISTS)? multipartIdentifier ; replaceTableHeader : (CREATE OR)? REPLACE TABLE multipartIdentifier ; bucketSpec : CLUSTERED BY identifierList (SORTED BY orderedIdentifierList)? INTO INTEGER_VALUE BUCKETS ; skewSpec : SKEWED BY identifierList ON (constantList | nestedConstantList) (STORED AS DIRECTORIES)? ; locationSpec : LOCATION STRING ; query : ctes? queryTerm queryOrganization ; insertInto : INSERT OVERWRITE TABLE? multipartIdentifier (partitionSpec (IF NOT EXISTS)?)? #insertOverwriteTable | INSERT INTO TABLE? multipartIdentifier partitionSpec? (IF NOT EXISTS)? #insertIntoTable | INSERT OVERWRITE LOCAL? DIRECTORY path=STRING rowFormat? createFileFormat? #insertOverwriteHiveDir | INSERT OVERWRITE LOCAL? DIRECTORY (path=STRING)? tableProvider (OPTIONS options=tablePropertyList)? #insertOverwriteDir ; partitionSpecLocation : partitionSpec locationSpec? ; partitionSpec : PARTITION '(' partitionVal (',' partitionVal)* ')' ; partitionVal : identifier (EQ constant)? ; database : DATABASE | SCHEMA ; describeFuncName : qualifiedName | STRING | comparisonOperator | arithmeticOperator | predicateOperator ; describeColName : nameParts+=identifier ('.' nameParts+=identifier)* ; ctes : WITH namedQuery (',' namedQuery)* ; namedQuery : name=errorCapturingIdentifier (columnAliases=identifierList)? AS? '(' query ')' ; tableProvider : USING multipartIdentifier ; tablePropertyList : '(' tableProperty (',' tableProperty)* ')' ; tableProperty : key=tablePropertyKey (EQ? value=tablePropertyValue)? ; tablePropertyKey : identifier ('.' identifier)* | STRING ; tablePropertyValue : INTEGER_VALUE | DECIMAL_VALUE | booleanValue | STRING ; constantList : '(' constant (',' constant)* ')' ; nestedConstantList : '(' constantList (',' constantList)* ')' ; createFileFormat : STORED AS fileFormat | STORED BY storageHandler ; fileFormat : INPUTFORMAT inFmt=STRING OUTPUTFORMAT outFmt=STRING #tableFileFormat | identifier #genericFileFormat ; storageHandler : STRING (WITH SERDEPROPERTIES tablePropertyList)? ; resource : identifier STRING ; dmlStatementNoWith : insertInto queryTerm queryOrganization #singleInsertQuery | fromClause multiInsertQueryBody+ #multiInsertQuery ; queryOrganization : (ORDER BY order+=sortItem (',' order+=sortItem)*)? (CLUSTER BY clusterBy+=expression (',' clusterBy+=expression)*)? (DISTRIBUTE BY distributeBy+=expression (',' distributeBy+=expression)*)? (SORT BY sort+=sortItem (',' sort+=sortItem)*)? windowClause? (LIMIT (ALL | limit=expression))? ; multiInsertQueryBody : insertInto fromStatementBody ; queryTerm : queryPrimary #queryTermDefault | left=queryTerm {legacy_setops_precedence_enbled}? operator=(INTERSECT | UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=INTERSECT setQuantifier? right=queryTerm #setOperation | left=queryTerm {!legacy_setops_precedence_enbled}? operator=(UNION | EXCEPT | SETMINUS) setQuantifier? right=queryTerm #setOperation ; queryPrimary : querySpecification #queryPrimaryDefault | fromStatement #fromStmt | TABLE multipartIdentifier #table | inlineTable #inlineTableDefault1 | '(' query ')' #subquery ; sortItem : expression ordering=(ASC | DESC)? (NULLS nullOrder=(LAST | FIRST))? ; fromStatement : fromClause fromStatementBody+ ; fromStatementBody : transformClause whereClause? queryOrganization | selectClause lateralView* whereClause? aggregationClause? havingClause? windowClause? queryOrganization ; querySpecification : transformClause fromClause? whereClause? #transformQuerySpecification | selectClause fromClause? lateralView* whereClause? aggregationClause? havingClause? windowClause? #regularQuerySpecification ; transformClause : (SELECT kind=TRANSFORM '(' namedExpressionSeq ')' | kind=MAP namedExpressionSeq | kind=REDUCE namedExpressionSeq) inRowFormat=rowFormat? (RECORDWRITER recordWriter=STRING)? USING script=STRING (AS (identifierSeq | colTypeList | ('(' (identifierSeq | colTypeList) ')')))? outRowFormat=rowFormat? (RECORDREADER recordReader=STRING)? ; selectClause : SELECT (hints+=hint)* setQuantifier? namedExpressionSeq ; setClause : SET assignmentList ; matchedClause : WHEN MATCHED (AND matchedCond=booleanExpression)? THEN matchedAction ; notMatchedClause : WHEN NOT MATCHED (AND notMatchedCond=booleanExpression)? THEN notMatchedAction ; matchedAction : DELETE | UPDATE SET ASTERISK | UPDATE SET assignmentList ; notMatchedAction : INSERT ASTERISK | INSERT '(' columns=multipartIdentifierList ')' VALUES '(' expression (',' expression)* ')' ; assignmentList : assignment (',' assignment)* ; assignment : key=multipartIdentifier EQ value=expression ; whereClause : WHERE booleanExpression ; havingClause : HAVING booleanExpression ; hint : '/*+' hintStatements+=hintStatement (','? hintStatements+=hintStatement)* '*/' ; hintStatement : hintName=identifier | hintName=identifier '(' parameters+=primaryExpression (',' parameters+=primaryExpression)* ')' ; fromClause : FROM relation (',' relation)* lateralView* pivotClause? ; aggregationClause : GROUP BY groupingExpressions+=expression (',' groupingExpressions+=expression)* ( WITH kind=ROLLUP | WITH kind=CUBE | kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')')? | GROUP BY kind=GROUPING SETS '(' groupingSet (',' groupingSet)* ')' ; groupingSet : '(' (expression (',' expression)*)? ')' | expression ; pivotClause : PIVOT '(' aggregates=namedExpressionSeq FOR pivotColumn IN '(' pivotValues+=pivotValue (',' pivotValues+=pivotValue)* ')' ')' ; pivotColumn : identifiers+=identifier | '(' identifiers+=identifier (',' identifiers+=identifier)* ')' ; pivotValue : expression (AS? identifier)? ; lateralView : LATERAL VIEW (OUTER)? qualifiedName '(' (expression (',' expression)*)? ')' tblName=identifier (AS? colName+=identifier (',' colName+=identifier)*)? ; setQuantifier : DISTINCT | ALL ; relation : relationPrimary joinRelation* ; joinRelation : (joinType) JOIN right=relationPrimary joinCriteria? | NATURAL joinType JOIN right=relationPrimary ; joinType : INNER? | CROSS | LEFT OUTER? | LEFT? SEMI | RIGHT OUTER? | FULL OUTER? | LEFT? ANTI ; joinCriteria : ON booleanExpression | USING identifierList ; sample : TABLESAMPLE '(' sampleMethod? ')' ; sampleMethod : negativeSign=MINUS? percentage=(INTEGER_VALUE | DECIMAL_VALUE) PERCENTLIT #sampleByPercentile | expression ROWS #sampleByRows | sampleType=BUCKET numerator=INTEGER_VALUE OUT OF denominator=INTEGER_VALUE (ON (identifier | qualifiedName '(' ')'))? #sampleByBucket | bytes=expression #sampleByBytes ; identifierList : '(' identifierSeq ')' ; identifierSeq : ident+=errorCapturingIdentifier (',' ident+=errorCapturingIdentifier)* ; orderedIdentifierList : '(' orderedIdentifier (',' orderedIdentifier)* ')' ; orderedIdentifier : ident=errorCapturingIdentifier ordering=(ASC | DESC)? ; identifierCommentList : '(' identifierComment (',' identifierComment)* ')' ; identifierComment : identifier (COMMENT STRING)? ; relationPrimary : multipartIdentifier sample? tableAlias #tableName | '(' query ')' sample? tableAlias #aliasedQuery | '(' relation ')' sample? tableAlias #aliasedRelation | inlineTable #inlineTableDefault2 | functionTable #tableValuedFunction ; inlineTable : VALUES expression (',' expression)* tableAlias ; functionTable : funcName=errorCapturingIdentifier '(' (expression (',' expression)*)? ')' tableAlias ; tableAlias : (AS? strictIdentifier identifierList?)? ; rowFormat : ROW FORMAT SERDE name=STRING (WITH SERDEPROPERTIES props=tablePropertyList)? #rowFormatSerde | ROW FORMAT DELIMITED (FIELDS TERMINATED BY fieldsTerminatedBy=STRING (ESCAPED BY escapedBy=STRING)?)? (COLLECTION ITEMS TERMINATED BY collectionItemsTerminatedBy=STRING)? (MAP KEYS TERMINATED BY keysTerminatedBy=STRING)? (LINES TERMINATED BY linesSeparatedBy=STRING)? (NULL DEFINED AS nullDefinedAs=STRING)? #rowFormatDelimited ; multipartIdentifierList : multipartIdentifier (',' multipartIdentifier)* ; multipartIdentifier : parts+=errorCapturingIdentifier ('.' parts+=errorCapturingIdentifier)* ; tableIdentifier : (db=errorCapturingIdentifier '.')? table=errorCapturingIdentifier ; functionIdentifier : (db=errorCapturingIdentifier '.')? function=errorCapturingIdentifier ; namedExpression : expression (AS? (name=errorCapturingIdentifier | identifierList))? ; namedExpressionSeq : namedExpression (',' namedExpression)* ; transformList : '(' transforms+=transform (',' transforms+=transform)* ')' ; transform : qualifiedName #identityTransform | transformName=identifier '(' argument+=transformArgument (',' argument+=transformArgument)* ')' #applyTransform ; transformArgument : qualifiedName | constant ; expression : booleanExpression ; booleanExpression : NOT booleanExpression #logicalNot | EXISTS '(' query ')' #exists | valueExpression predicate? #predicated | left=booleanExpression operator=AND right=booleanExpression #logicalBinary | left=booleanExpression operator=OR right=booleanExpression #logicalBinary ; predicate : NOT? kind=BETWEEN lower=valueExpression AND upper=valueExpression | NOT? kind=IN '(' expression (',' expression)* ')' | NOT? kind=IN '(' query ')' | NOT? kind=(RLIKE | LIKE) pattern=valueExpression | IS NOT? kind=NULL | IS NOT? kind=(TRUE | FALSE | UNKNOWN) | IS NOT? kind=DISTINCT FROM right=valueExpression ; valueExpression : primaryExpression #valueExpressionDefault | operator=(MINUS | PLUS | TILDE) valueExpression #arithmeticUnary | left=valueExpression operator=(ASTERISK | SLASH | PERCENT | DIV) right=valueExpression #arithmeticBinary | left=valueExpression operator=(PLUS | MINUS | CONCAT_PIPE) right=valueExpression #arithmeticBinary | left=valueExpression operator=AMPERSAND right=valueExpression #arithmeticBinary | left=valueExpression operator=HAT right=valueExpression #arithmeticBinary | left=valueExpression operator=PIPE right=valueExpression #arithmeticBinary | left=valueExpression comparisonOperator right=valueExpression #comparison ; primaryExpression : name=(CURRENT_DATE | CURRENT_TIMESTAMP) #currentDatetime | CASE whenClause+ (ELSE elseExpression=expression)? END #searchedCase | CASE value=expression whenClause+ (ELSE elseExpression=expression)? END #simpleCase | CAST '(' expression AS dataType ')' #cast | STRUCT '(' (argument+=namedExpression (',' argument+=namedExpression)*)? ')' #struct | (FIRST | FIRST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #first | (LAST | LAST_VALUE) '(' expression ((IGNORE | RESPECT) NULLS)? ')' #last | POSITION '(' substr=valueExpression IN str=valueExpression ')' #position | constant #constantDefault | ASTERISK #star | qualifiedName '.' ASTERISK #star | '(' namedExpression (',' namedExpression)+ ')' #rowConstructor | '(' query ')' #subqueryExpression | qualifiedName '(' (setQuantifier? argument+=expression (',' argument+=expression)*)? ')' (OVER windowSpec)? #functionCall | identifier '->' expression #lambda | '(' identifier (',' identifier)+ ')' '->' expression #lambda | value=primaryExpression '[' index=valueExpression ']' #subscript | identifier #columnReference | base=primaryExpression '.' fieldName=identifier #dereference | '(' expression ')' #parenthesizedExpression | EXTRACT '(' field=identifier FROM source=valueExpression ')' #extract | (SUBSTR | SUBSTRING) '(' str=valueExpression (FROM | ',') pos=valueExpression ((FOR | ',') len=valueExpression)? ')' #substring | TRIM '(' trimOption=(BOTH | LEADING | TRAILING)? (trimStr=valueExpression)? FROM srcStr=valueExpression ')' #trim | OVERLAY '(' input=valueExpression PLACING replace=valueExpression FROM position=valueExpression (FOR length=valueExpression)? ')' #overlay ; constant : NULL #nullLiteral | interval #intervalLiteral | negativeSign=MINUS? identifier STRING #typeConstructor | number #numericLiteral | booleanValue #booleanLiteral | STRING+ #stringLiteral ; comparisonOperator : EQ | NEQ | NEQJ | LT | LTE | GT | GTE | NSEQ ; arithmeticOperator : PLUS | MINUS | ASTERISK | SLASH | PERCENT | DIV | TILDE | AMPERSAND | PIPE | CONCAT_PIPE | HAT ; predicateOperator : OR | AND | IN | NOT ; booleanValue : TRUE | FALSE ; interval : negativeSign=MINUS? INTERVAL (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval)? | {ansi}? (errorCapturingMultiUnitsInterval | errorCapturingUnitToUnitInterval) ; errorCapturingMultiUnitsInterval : multiUnitsInterval unitToUnitInterval? ; multiUnitsInterval : (intervalValue intervalUnit)+ ; errorCapturingUnitToUnitInterval : body=unitToUnitInterval (error1=multiUnitsInterval | error2=unitToUnitInterval)? ; unitToUnitInterval : value=intervalValue from=intervalUnit TO to=intervalUnit ; intervalValue : (PLUS | MINUS)? (INTEGER_VALUE | DECIMAL_VALUE) | STRING ; intervalUnit : DAY | DAYS | HOUR | HOURS | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | SECOND | SECONDS | WEEK | WEEKS | YEAR | YEARS ; colPosition : FIRST | AFTER multipartIdentifier ; dataType : complex=ARRAY '<' dataType '>' #complexDataType | complex=MAP '<' dataType ',' dataType '>' #complexDataType | complex=STRUCT ('<' complexColTypeList? '>' | NEQ) #complexDataType | identifier ('(' INTEGER_VALUE (',' INTEGER_VALUE)* ')')? #primitiveDataType ; qualifiedColTypeWithPositionList : qualifiedColTypeWithPosition (',' qualifiedColTypeWithPosition)* ; qualifiedColTypeWithPosition : name=multipartIdentifier dataType (COMMENT comment=STRING)? colPosition? ; colTypeList : colType (',' colType)* ; colType : colName=errorCapturingIdentifier dataType (COMMENT STRING)? ; complexColTypeList : complexColType (',' complexColType)* ; complexColType : identifier ':' dataType (COMMENT STRING)? ; whenClause : WHEN condition=expression THEN result=expression ; windowClause : WINDOW namedWindow (',' namedWindow)* ; namedWindow : name=errorCapturingIdentifier AS windowSpec ; windowSpec : name=errorCapturingIdentifier #windowRef | '('name=errorCapturingIdentifier')' #windowRef | '(' ( CLUSTER BY partition+=expression (',' partition+=expression)* | ((PARTITION | DISTRIBUTE) BY partition+=expression (',' partition+=expression)*)? ((ORDER | SORT) BY sortItem (',' sortItem)*)?) windowFrame? ')' #windowDef ; windowFrame : frameType=RANGE start=frameBound | frameType=ROWS start=frameBound | frameType=RANGE BETWEEN start=frameBound AND end=frameBound | frameType=ROWS BETWEEN start=frameBound AND end=frameBound ; frameBound : UNBOUNDED boundType=(PRECEDING | FOLLOWING) | boundType=CURRENT ROW | expression boundType=(PRECEDING | FOLLOWING) ; qualifiedNameList : qualifiedName (',' qualifiedName)* ; qualifiedName : identifier ('.' identifier)* ; // this rule is used for explicitly capturing wrong identifiers such as test-table, which should actually be `test-table` // replace identifier with errorCapturingIdentifier where the immediate follow symbol is not an expression, otherwise // valid expressions such as ""a-b"" can be recognized as an identifier errorCapturingIdentifier : identifier errorCapturingIdentifierExtra ; // extra left-factoring grammar errorCapturingIdentifierExtra : (MINUS identifier)+ #errorIdent | #realIdent ; identifier : strictIdentifier | {!ansi}? strictNonReserved ; strictIdentifier : IDENTIFIER #unquotedIdentifier | quotedIdentifier #quotedIdentifierAlternative | {ansi}? ansiNonReserved #unquotedIdentifier | {!ansi}? nonReserved #unquotedIdentifier ; quotedIdentifier : BACKQUOTED_IDENTIFIER ; number : MINUS? DECIMAL_VALUE #decimalLiteral | MINUS? INTEGER_VALUE #integerLiteral | MINUS? BIGINT_LITERAL #bigIntLiteral | MINUS? SMALLINT_LITERAL #smallIntLiteral | MINUS? TINYINT_LITERAL #tinyIntLiteral | MINUS? DOUBLE_LITERAL #doubleLiteral | MINUS? BIGDECIMAL_LITERAL #bigDecimalLiteral ; // When `spark.sql.ansi.enabled=true`, there are 2 kinds of keywords in Spark SQL. // - Reserved keywords: // Keywords that are reserved and can't be used as identifiers for table, view, column, // function, alias, etc. // - Non-reserved keywords: // Keywords that have a special meaning only in particular contexts and can be used as // identifiers in other contexts. For example, `SELECT 1 WEEK` is an interval literal, but WEEK // can be used as identifiers in other places. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The non-reserved keywords are listed below. Keywords not in this list are reserved keywords. ansiNonReserved : ADD | AFTER | ALTER | ANALYZE | ARCHIVE | ARRAY | ASC | AT | BETWEEN | BUCKET | BUCKETS | BY | CACHE | CASCADE | CHANGE | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLECTION | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | COST | CUBE | CURRENT | DATA | DATABASE | DATABASES | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTRIBUTE | DIV | DROP | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FIELDS | FILEFORMAT | FIRST | FOLLOWING | FORMAT | FORMATTED | FUNCTION | FUNCTIONS | GLOBAL | GROUPING | HOURS | IF | IGNORE | IMPORT | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | ITEMS | KEYS | LAST | LATERAL | LAZY | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTES | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NULLS | OF | OPTION | OPTIONS | OUT | OUTPUTFORMAT | OVER | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECONDS | SEPARATED | SERDE | SERDEPROPERTIES | SET | SETS | SHOW | SKEWED | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | TOUCH | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | UNARCHIVE | UNBOUNDED | UNCACHE | UNLOCK | UNSET | UPDATE | USE | VALUES | VIEW | WEEK | WEEKS | WINDOW | YEARS ; // When `spark.sql.ansi.enabled=false`, there are 2 kinds of keywords in Spark SQL. // - Non-reserved keywords: // Same definition as the one when `spark.sql.ansi.enabled=true`. // - Strict-non-reserved keywords: // A strict version of non-reserved keywords, which can not be used as table alias. // You can find the full keywords list by searching ""Start of the keywords list"" in this file. // The strict-non-reserved keywords are listed in `strictNonReserved`. // The non-reserved keywords are listed in `nonReserved`. // These 2 together contain all the keywords. strictNonReserved : ANTI | CROSS | EXCEPT | FULL | INNER | INTERSECT | JOIN | LEFT | NATURAL | ON | RIGHT | SEMI | SETMINUS | UNION | USING ; nonReserved : ADD | AFTER | ALL | ALTER | ANALYZE | AND | ANY | ARCHIVE | ARRAY | AS | ASC | AT | AUTHORIZATION | BETWEEN | BOTH | BUCKET | BUCKETS | BY | CACHE | CASCADE | CASE | CAST | CHANGE | CHECK | CLEAR | CLUSTER | CLUSTERED | CODEGEN | COLLATE | COLLECTION | COLUMN | COLUMNS | COMMENT | COMMIT | COMPACT | COMPACTIONS | COMPUTE | CONCATENATE | CONSTRAINT | COST | CREATE | CUBE | CURRENT | CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP | CURRENT_USER | DATA | DATABASE | DATABASES | DAY | DAYS | DBPROPERTIES | DEFINED | DELETE | DELIMITED | DESC | DESCRIBE | DFS | DIRECTORIES | DIRECTORY | DISTINCT | DISTRIBUTE | DIV | DROP | ELSE | END | ESCAPED | EXCHANGE | EXISTS | EXPLAIN | EXPORT | EXTENDED | EXTERNAL | EXTRACT | FALSE | FETCH | FIELDS | FILEFORMAT | FIRST | FIRST_VALUE | FOLLOWING | FOR | FOREIGN | FORMAT | FORMATTED | FROM | FUNCTION | FUNCTIONS | GLOBAL | GRANT | GROUP | GROUPING | HAVING | HOUR | HOURS | IF | IGNORE | IMPORT | IN | INDEX | INDEXES | INPATH | INPUTFORMAT | INSERT | INTERVAL | INTO | IS | ITEMS | KEYS | LAST | LAST_VALUE | LATERAL | LAZY | LEADING | LIKE | LIMIT | LINES | LIST | LOAD | LOCAL | LOCATION | LOCK | LOCKS | LOGICAL | MACRO | MAP | MATCHED | MERGE | MICROSECOND | MICROSECONDS | MILLISECOND | MILLISECONDS | MINUTE | MINUTES | MONTH | MONTHS | MSCK | NAMESPACE | NAMESPACES | NO | NOT | NULL | NULLS | OF | ONLY | OPTION | OPTIONS | OR | ORDER | OUT | OUTER | OUTPUTFORMAT | OVER | OVERLAPS | OVERLAY | OVERWRITE | PARTITION | PARTITIONED | PARTITIONS | PERCENTLIT | PIVOT | PLACING | POSITION | PRECEDING | PRIMARY | PRINCIPALS | PROPERTIES | PURGE | QUERY | RANGE | RECORDREADER | RECORDWRITER | RECOVER | REDUCE | REFERENCES | REFRESH | RENAME | REPAIR | REPLACE | RESET | RESPECT | RESTRICT | REVOKE | RLIKE | ROLE | ROLES | ROLLBACK | ROLLUP | ROW | ROWS | SCHEMA | SECOND | SECONDS | SELECT | SEPARATED | SERDE | SERDEPROPERTIES | SESSION_USER | SET | SETS | SHOW | SKEWED | SOME | SORT | SORTED | START | STATISTICS | STORED | STRATIFY | STRUCT | SUBSTR | SUBSTRING | TABLE | TABLES | TABLESAMPLE | TBLPROPERTIES | TEMPORARY | TERMINATED | THEN | TO | TOUCH | TRAILING | TRANSACTION | TRANSACTIONS | TRANSFORM | TRIM | TRUE | TRUNCATE | TYPE | UNARCHIVE | UNBOUNDED | UNCACHE | UNIQUE | UNKNOWN | UNLOCK | UNSET | UPDATE | USE | USER | VALUES | VIEW | WEEK | WEEKS | WHEN | WHERE | WINDOW | WITH | YEAR | YEARS ; // NOTE: If you add a new token in the list below, you should update the list of keywords // in `docs/sql-keywords.md`. If the token is a non-reserved keyword, // please update `ansiNonReserved` and `nonReserved` as well. //============================ // Start of the keywords list //============================ ADD: 'ADD'; AFTER: 'AFTER'; ALL: 'ALL'; ALTER: 'ALTER'; ANALYZE: 'ANALYZE'; AND: 'AND'; ANTI: 'ANTI'; ANY: 'ANY'; ARCHIVE: 'ARCHIVE'; ARRAY: 'ARRAY'; AS: 'AS'; ASC: 'ASC'; AT: 'AT'; AUTHORIZATION: 'AUTHORIZATION'; BETWEEN: 'BETWEEN'; BOTH: 'BOTH'; BUCKET: 'BUCKET'; BUCKETS: 'BUCKETS'; BY: 'BY'; CACHE: 'CACHE'; CASCADE: 'CASCADE'; CASE: 'CASE'; CAST: 'CAST'; CHANGE: 'CHANGE'; CHECK: 'CHECK'; CLEAR: 'CLEAR'; CLUSTER: 'CLUSTER'; CLUSTERED: 'CLUSTERED'; CODEGEN: 'CODEGEN'; COLLATE: 'COLLATE'; COLLECTION: 'COLLECTION'; COLUMN: 'COLUMN'; COLUMNS: 'COLUMNS'; COMMENT: 'COMMENT'; COMMIT: 'COMMIT'; COMPACT: 'COMPACT'; COMPACTIONS: 'COMPACTIONS'; COMPUTE: 'COMPUTE'; CONCATENATE: 'CONCATENATE'; CONSTRAINT: 'CONSTRAINT'; COST: 'COST'; CREATE: 'CREATE'; CROSS: 'CROSS'; CUBE: 'CUBE'; CURRENT: 'CURRENT'; CURRENT_DATE: 'CURRENT_DATE'; CURRENT_TIME: 'CURRENT_TIME'; CURRENT_TIMESTAMP: 'CURRENT_TIMESTAMP'; CURRENT_USER: 'CURRENT_USER'; DATA: 'DATA'; DATABASE: 'DATABASE'; DATABASES: 'DATABASES' | 'SCHEMAS'; DAY: 'DAY'; DAYS: 'DAYS'; DBPROPERTIES: 'DBPROPERTIES'; DEFINED: 'DEFINED'; DELETE: 'DELETE'; DELIMITED: 'DELIMITED'; DESC: 'DESC'; DESCRIBE: 'DESCRIBE'; DFS: 'DFS'; DIRECTORIES: 'DIRECTORIES'; DIRECTORY: 'DIRECTORY'; DISTINCT: 'DISTINCT'; DISTRIBUTE: 'DISTRIBUTE'; DROP: 'DROP'; ELSE: 'ELSE'; END: 'END'; ESCAPED: 'ESCAPED'; EXCEPT: 'EXCEPT'; EXCHANGE: 'EXCHANGE'; EXISTS: 'EXISTS'; EXPLAIN: 'EXPLAIN'; EXPORT: 'EXPORT'; EXTENDED: 'EXTENDED'; EXTERNAL: 'EXTERNAL'; EXTRACT: 'EXTRACT'; FALSE: 'FALSE'; FETCH: 'FETCH'; FIELDS: 'FIELDS'; FILEFORMAT: 'FILEFORMAT'; FIRST: 'FIRST'; FIRST_VALUE: 'FIRST_VALUE'; FOLLOWING: 'FOLLOWING'; FOR: 'FOR'; FOREIGN: 'FOREIGN'; FORMAT: 'FORMAT'; FORMATTED: 'FORMATTED'; FROM: 'FROM'; FULL: 'FULL'; FUNCTION: 'FUNCTION'; FUNCTIONS: 'FUNCTIONS'; GLOBAL: 'GLOBAL'; GRANT: 'GRANT'; GROUP: 'GROUP'; GROUPING: 'GROUPING'; HAVING: 'HAVING'; HOUR: 'HOUR'; HOURS: 'HOURS'; IF: 'IF'; IGNORE: 'IGNORE'; IMPORT: 'IMPORT'; IN: 'IN'; INDEX: 'INDEX'; INDEXES: 'INDEXES'; INNER: 'INNER'; INPATH: 'INPATH'; INPUTFORMAT: 'INPUTFORMAT'; INSERT: 'INSERT'; INTERSECT: 'INTERSECT'; INTERVAL: 'INTERVAL'; INTO: 'INTO'; IS: 'IS'; ITEMS: 'ITEMS'; JOIN: 'JOIN'; KEYS: 'KEYS'; LAST: 'LAST'; LAST_VALUE: 'LAST_VALUE'; LATERAL: 'LATERAL'; LAZY: 'LAZY'; LEADING: 'LEADING'; LEFT: 'LEFT'; LIKE: 'LIKE'; LIMIT: 'LIMIT'; LINES: 'LINES'; LIST: 'LIST'; LOAD: 'LOAD'; LOCAL: 'LOCAL'; LOCATION: 'LOCATION'; LOCK: 'LOCK'; LOCKS: 'LOCKS'; LOGICAL: 'LOGICAL'; MACRO: 'MACRO'; MAP: 'MAP'; MATCHED: 'MATCHED'; MERGE: 'MERGE'; MICROSECOND: 'MICROSECOND'; MICROSECONDS: 'MICROSECONDS'; MILLISECOND: 'MILLISECOND'; MILLISECONDS: 'MILLISECONDS'; MINUTE: 'MINUTE'; MINUTES: 'MINUTES'; MONTH: 'MONTH'; MONTHS: 'MONTHS'; MSCK: 'MSCK'; NAMESPACE: 'NAMESPACE'; NAMESPACES: 'NAMESPACES'; NATURAL: 'NATURAL'; NO: 'NO'; NOT: 'NOT' | '!'; NULL: 'NULL'; NULLS: 'NULLS'; OF: 'OF'; ON: 'ON'; ONLY: 'ONLY'; OPTION: 'OPTION'; OPTIONS: 'OPTIONS'; OR: 'OR'; ORDER: 'ORDER'; OUT: 'OUT'; OUTER: 'OUTER'; OUTPUTFORMAT: 'OUTPUTFORMAT'; OVER: 'OVER'; OVERLAPS: 'OVERLAPS'; OVERLAY: 'OVERLAY'; OVERWRITE: 'OVERWRITE'; PARTITION: 'PARTITION'; PARTITIONED: 'PARTITIONED'; PARTITIONS: 'PARTITIONS'; PERCENTLIT: 'PERCENT'; PIVOT: 'PIVOT'; PLACING: 'PLACING'; POSITION: 'POSITION'; PRECEDING: 'PRECEDING'; PRIMARY: 'PRIMARY'; PRINCIPALS: 'PRINCIPALS'; PROPERTIES: 'PROPERTIES'; PURGE: 'PURGE'; QUERY: 'QUERY'; RANGE: 'RANGE'; RECORDREADER: 'RECORDREADER'; RECORDWRITER: 'RECORDWRITER'; RECOVER: 'RECOVER'; REDUCE: 'REDUCE'; REFERENCES: 'REFERENCES'; REFRESH: 'REFRESH'; RENAME: 'RENAME'; REPAIR: 'REPAIR'; REPLACE: 'REPLACE'; RESET: 'RESET'; RESPECT: 'RESPECT'; RESTRICT: 'RESTRICT'; REVOKE: 'REVOKE'; RIGHT: 'RIGHT'; RLIKE: 'RLIKE' | 'REGEXP'; ROLE: 'ROLE'; ROLES: 'ROLES'; ROLLBACK: 'ROLLBACK'; ROLLUP: 'ROLLUP'; ROW: 'ROW'; ROWS: 'ROWS'; SCHEMA: 'SCHEMA'; SECOND: 'SECOND'; SECONDS: 'SECONDS'; SELECT: 'SELECT'; SEMI: 'SEMI'; SEPARATED: 'SEPARATED'; SERDE: 'SERDE'; SERDEPROPERTIES: 'SERDEPROPERTIES'; SESSION_USER: 'SESSION_USER'; SET: 'SET'; SETMINUS: 'MINUS'; SETS: 'SETS'; SHOW: 'SHOW'; SKEWED: 'SKEWED'; SOME: 'SOME'; SORT: 'SORT'; SORTED: 'SORTED'; START: 'START'; STATISTICS: 'STATISTICS'; STORED: 'STORED'; STRATIFY: 'STRATIFY'; STRUCT: 'STRUCT'; SUBSTR: 'SUBSTR'; SUBSTRING: 'SUBSTRING'; TABLE: 'TABLE'; TABLES: 'TABLES'; TABLESAMPLE: 'TABLESAMPLE'; TBLPROPERTIES: 'TBLPROPERTIES'; TEMPORARY: 'TEMPORARY' | 'TEMP'; TERMINATED: 'TERMINATED'; THEN: 'THEN'; TO: 'TO'; TOUCH: 'TOUCH'; TRAILING: 'TRAILING'; TRANSACTION: 'TRANSACTION'; TRANSACTIONS: 'TRANSACTIONS'; TRANSFORM: 'TRANSFORM'; TRIM: 'TRIM'; TRUE: 'TRUE'; TRUNCATE: 'TRUNCATE'; TYPE: 'TYPE'; UNARCHIVE: 'UNARCHIVE'; UNBOUNDED: 'UNBOUNDED'; UNCACHE: 'UNCACHE'; UNION: 'UNION'; UNIQUE: 'UNIQUE'; UNKNOWN: 'UNKNOWN'; UNLOCK: 'UNLOCK'; UNSET: 'UNSET'; UPDATE: 'UPDATE'; USE: 'USE'; USER: 'USER'; USING: 'USING'; VALUES: 'VALUES'; VIEW: 'VIEW'; WEEK: 'WEEK'; WEEKS: 'WEEKS'; WHEN: 'WHEN'; WHERE: 'WHERE'; WINDOW: 'WINDOW'; WITH: 'WITH'; YEAR: 'YEAR'; YEARS: 'YEARS'; //============================ // End of the keywords list //============================ EQ : '=' | '=='; NSEQ: '<=>'; NEQ : '<>'; NEQJ: '!='; LT : '<'; LTE : '<=' | '!>'; GT : '>'; GTE : '>=' | '!<'; PLUS: '+'; MINUS: '-'; ASTERISK: '*'; SLASH: '/'; PERCENT: '%'; DIV: 'DIV'; TILDE: '~'; AMPERSAND: '&'; PIPE: '|'; CONCAT_PIPE: '||'; HAT: '^'; STRING : '\\'' ( ~('\\''|'\\\\') | ('\\\\' .) )* '\\'' | '""' ( ~('""'|'\\\\') | ('\\\\' .) )* '""' ; BIGINT_LITERAL : DIGIT+ 'L' ; SMALLINT_LITERAL : DIGIT+ 'S' ; TINYINT_LITERAL : DIGIT+ 'Y' ; INTEGER_VALUE : DIGIT+ ; DECIMAL_VALUE : DIGIT+ EXPONENT | DECIMAL_DIGITS EXPONENT? {isValidDecimal()}? ; DOUBLE_LITERAL : DIGIT+ EXPONENT? 'D' | DECIMAL_DIGITS EXPONENT? 'D' {isValidDecimal()}? ; BIGDECIMAL_LITERAL : DIGIT+ EXPONENT? 'BD' | DECIMAL_DIGITS EXPONENT? 'BD' {isValidDecimal()}? ; IDENTIFIER : (LETTER | DIGIT | '_')+ ; BACKQUOTED_IDENTIFIER : '`' ( ~'`' | '``' )* '`' ; fragment DECIMAL_DIGITS : DIGIT+ '.' DIGIT* | '.' DIGIT+ ; fragment EXPONENT : 'E' [+-]? DIGIT+ ; fragment DIGIT : [0-9] ; fragment LETTER : [A-Z] ; SIMPLE_COMMENT : '--' ~[\\r\\n]* '\\r'? '\\n'? -> channel(HIDDEN) ; BRACKETED_EMPTY_COMMENT : '/**/' -> channel(HIDDEN) ; BRACKETED_COMMENT : '/*' ~[+] .*? '*/' -> channel(HIDDEN) ; WS : [ \\r\\n\\t]+ -> channel(HIDDEN) ; // Catch-all for anything we can't recognize. // We use this to be able to ignore and recover all the text // when splitting statements with DelimiterLexer UNRECOGNIZED : . ; ",12351,False,2315.2110565214225,median "<%@ Control Language=""C#"" AutoEventWireup=""true"" CodeFile=""FileMgr.ascx.cs"" Inherits=""Modules_FileManager_FileMgr"" %>

    File Manager

    • Add File
    • Delete File
    • Add Folder
    • Delete Folder
    • Copy
    • Move
    • Refresh
    <%-- --%>
    FileMgrPopUpclose
    <%-- --%>
    Browse Files:
    Add New Folderclose
    FolderName:
    Type: Standard <%-- --%>
    FileMgrPopUpclose

    Edit Image

    Download
    X1 Y1 X2 Y2
    W H
    Download
    Rename Fileclose
    <%-- --%> <%-- --%>
    FileName:
    File Mode: Archive
    Read
    Write
    Hidden
    Message close

    Add New Folderclose
    Confirmationclose
    ",16307,True,2771.828986003603,median " JavaScript Tutorial
    THE WORLD'S LARGEST WEB DEVELOPER SITE
    ×

    JS Tutorial

    JS HOME JS Introduction JS Where To JS Output JS Syntax JS Statements JS Comments JS Variables JS Operators JS Arithmetic JS Assignment JS Data Types JS Functions JS Objects JS Scope JS Events JS Strings JS String Methods JS Numbers JS Number Methods JS Math JS Random JS Dates JS Date Formats JS Date Methods JS Arrays JS Array Methods JS Array Sort JS Booleans JS Comparisons JS Conditions JS Switch JS Loop For JS Loop While JS Break JS Type Conversion JS Bitwise JS RegExp JS Errors JS Debugging JS Hoisting JS Strict Mode JS Style Guide JS Best Practices JS Mistakes JS Performance JS Reserved Words JS Versions JS JSON

    JS Forms

    JS Forms Forms API

    JS Objects

    Object Definitions Object Properties Object Methods Object Prototypes

    JS Functions

    Function Definitions Function Parameters Function Invocation Function Call Function Apply Function Closures

    JS HTML DOM

    DOM Intro DOM Methods DOM Document DOM Elements DOM HTML DOM CSS DOM Animations DOM Events DOM Event Listener DOM Navigation DOM Nodes DOM Collections DOM Node Lists

    JS Browser BOM

    JS Window JS Screen JS Location JS History JS Navigator JS Popup Alert JS Timing JS Cookies

    JS AJAX

    AJAX Intro AJAX XMLHttp AJAX Request AJAX Response AJAX XML File AJAX PHP AJAX ASP AJAX Database AJAX Applications AJAX Examples

    JS JSON

    JSON Intro JSON Syntax JSON vs XML JSON Data Types JSON Objects JSON Arrays JSON Parse JSON Stringify JSON PHP JSON HTML JSON JSONP

    JS Examples

    JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Quiz JS Certificate

    JS References

    JavaScript Objects HTML DOM Objects


    JavaScript Tutorial

    JavaScript is the programming language of HTML and the Web.

    JavaScript is easy to learn.

    This tutorial will teach you JavaScript from basic to advanced.


    Examples in Each Chapter

    With our "Try it Yourself" editor, you can change all examples and view the results.

    Example

    My First JavaScript

    Try it Yourself »

    We recommend reading this tutorial, in the sequence listed in the left menu.


    Learn by Examples

    Examples are better than 1000 words. Examples are often easier to understand than text explanations.

    This tutorial supplements all explanations with clarifying "Try it Yourself" examples.

    JavaScript Examples

    If you try all the examples, you will learn a lot about JavaScript, in a very short time!


    Why Study JavaScript?

    JavaScript is one of the 3 languages all web developers must learn:

       1. HTML to define the content of web pages

       2. CSS to specify the layout of web pages

       3. JavaScript to program the behavior of web pages

    This tutorial is about JavaScript, and how JavaScript works with HTML and CSS.

    Did You Know?

    JavaScript and Java are completely different languages, both in concept and design.

    JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
    ECMA-262 is the official name of the standard. ECMAScript is the official name of the language.

    You can read more about the different JavaScript versions in the chapter JS Versions.



    Learning Speed

    In this tutorial, the learning speed is your choice.

    Everything is up to you.

    If you are struggling, take a break, or reread the material.

    Always make sure you understand all the "Try-it-Yourself" examples.


    JavaScript References

    W3Schools maintains a complete JavaScript reference, including all HTML and browser objects.

    The reference contains examples for all properties and methods, and is continuously updated according to the latest web standards.

    Complete JavaScript Reference


    JavaScript Quiz Test

    Test your JavaScript skills at W3Schools!

    Start JavaScript Quiz!


    JavaScript Exam - Get Your Diploma!

    W3Schools' Online Certification

    The perfect solution for professionals who need to balance work, family, and career building.

    More than 10 000 certificates already issued!

    Get Your Certificate »

    The HTML Certificate documents your knowledge of HTML.

    The CSS Certificate documents your knowledge of advanced CSS.

    The JavaScript Certificate documents your knowledge of JavaScript and HTML DOM.

    The jQuery Certificate documents your knowledge of jQuery.

    The PHP Certificate documents your knowledge of PHP and SQL (MySQL).

    The XML Certificate documents your knowledge of XML, XML DOM and XSLT.

    The Bootstrap Certificate documents your knowledge of the Bootstrap framework.


    SHARE



    CERTIFICATES

    HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML.

    Read More »



    ×

    Your Suggestion:


    ×

    Thank You For Helping Us!

    Your message has been sent to W3Schools.


    W3Schools is optimized for learning, testing, and training. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 1999-2017 by Refsnes Data. All Rights Reserved.
    Powered by W3.CSS.



    ",16264,False,2425.86378820242,median