text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
  <meta name="description" content="bootstrap admin template">
  <meta name="author" content="">
  <title>Bina Marga Prov Aceh</title>
  <?php echo $this->load->view('common/head', '', TRUE);?>

  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/css/bootstrap.min.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/css/bootstrap-extend.min.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/assets/css/site.min.css">

  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/animsition/animsition.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/asscrollable/asScrollable.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/switchery/switchery.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/intro-js/introjs.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/slidepanel/slidePanel.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/flag-icon-css/flag-icon.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/waves/waves.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/datatables-bootstrap/dataTables.bootstrap.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/datatables-fixedheader/dataTables.fixedHeader.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/datatables-responsive/dataTables.responsive.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/assets/examples/css/tables/datatable.css">

  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/fonts/font-awesome/font-awesome.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/fonts/material-design/material-design.min.css">
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/fonts/brand-icons/brand-icons.min.css">
  <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=Roboto:300,400,500,300italic'>
  <link rel="stylesheet" href="<?php echo site_url(); ?>assets/global/vendor/toastr/toastr.css">

  <?php echo $this->session->flashdata('pesan')?>
<?php echo $this->load->view('common/menu', '', TRUE);?>

Kabupaten

Kabupaten

                  <form class="form-horizontal" action="kabupaten/proses_tambah_kabupaten" method="post">

                      Nama Kabupaten/Kota

                        <input type="text" class="form-control" name="nama_kabupaten" required placeholder="Nama Kabupaten" autocomplete="off" required>

                        <button type="submit" class="btn btn-primary waves-effect waves-light">Submit </button>
                        <button type="reset" class="btn btn-warning waves-effect waves-light">Reset</button>

                  </form>

Data Kabupeten/Kota

                No
                Nama Kabupaten/Kota
                edit
                Hapus

                No
                Nama Kabupaten
                edit
                Hapus

              <?php
                 $i=0;
                 foreach($lihat as $data_kabupaten){
                 $i++;
               ?>

                  <?php echo $i; ?>
                  <?php echo $data_kabupaten->nama_kabupaten; ?>
                  <?php
                  echo"id_kabupaten' onclick=\"return confirm('Apakah Anda Yakin Menghapus ?')
                    \" title='Hapus'><button type='button' class='btn btn-warning'>Edit</button>
                    	";
                  ?>
                  <?php
                  echo"id_kabupaten' onclick=\"return confirm('Apakah Anda Yakin Menghapus ?')
                    \" title='Hapus'><button type='button' class='btn btn-danger'>Hapus</button>
                    	";
                  ?>

              <?php
               }
               ?>

  <?php echo $this->load->view('common/footer', '', TRUE);?>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <title>

    Microsoft SQL Server
 —
    SQLAlchemy 0.9 Documentation

        </title>

                <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
                <link rel="stylesheet" href="../_static/changelog.css" type="text/css" />
                <link rel="stylesheet" href="../_static/sphinx_paramlinks.css" type="text/css" />
                <link rel="stylesheet" href="../_static/docs.css" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
        <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="SQLAlchemy 0.9 Documentation" href="../index.html" />
        <link rel="up" title="Dialects" href="index.html" />
        <link rel="next" title="MySQL" href="mysql.html" />
        <link rel="prev" title="Firebird" href="firebird.html" />

        Release: 0.9.9 | Release Date: March 10, 2015

SQLAlchemy 0.9 Documentation

SQLAlchemy 0.9 Documentation

                Contents |
                Index

                <form class="search" action="../search.html" method="get">
                  <input type="text" name="q" size="12" /> <input type="submit" value="Search" />
                  <input type="hidden" name="check_keywords" value="yes" />
                  <input type="hidden" name="area" value="default" />
                </form>

            Dialects

Drizzle

Firebird

Microsoft SQL Server¶

Support for the Microsoft SQL Server database.

Auto Increment Behavior

Controlling “Start” and “Increment”

INSERT behavior

Collation Support

LIMIT/OFFSET Support

Nullability

Date / Time Handling

Clustered Index Support

MSSQL-Specific Index Options

INCLUDE

Index ordering

Compatibility Levels

Triggers

Enabling Snapshot Isolation

Known Issues

SQL Server Data Types

PyODBC

DBAPI

Connecting

Additional Connection Examples

Unicode Binds

mxODBC

DBAPI

Connecting

Execution Modes

pymssql

DBAPI

Connecting

zxjdbc

DBAPI

Connecting

AdoDBAPI

DBAPI

Connecting

MySQL

Oracle

PostgreSQL

SQLite

Sybase

Microsoft SQL Server¶

Support for the Microsoft SQL Server database.

DBAPI Support¶

The following dialect/DBAPI options are available.  Please refer to individual DBAPI sections for connect information.

PyODBC

mxODBC

pymssql

zxJDBC for Jython

adodbapi

Auto Increment Behavior¶

SQL Server provides so-called “auto incrementing” behavior using the
<tt class="docutils literal">IDENTITY</tt> construct, which can be placed on an integer primary key.
SQLAlchemy considers <tt class="docutils literal">IDENTITY</tt> within its default “autoincrement” behavior,
described at <tt class="xref py py-paramref docutils literal">Column.autoincrement</tt>; this means
that by default, the first integer primary key column in a <tt class="xref py py-class docutils literal">Table</tt>
will be considered to be the identity column and will generate DDL as such:

from sqlalchemy import Table, MetaData, Column, Integer

m = MetaData()
t = Table('t', m,
        Column('id', Integer, primary_key=True),
        Column('x', Integer))
m.create_all(engine)

The above example will generate DDL as:

CREATE TABLE t (
    id INTEGER NOT NULL IDENTITY(1,1),
    x INTEGER NULL,
    PRIMARY KEY (id)
)

For the case where this default generation of <tt class="docutils literal">IDENTITY</tt> is not desired,
specify <tt class="docutils literal">autoincrement=False</tt> on all integer primary key columns:

m = MetaData()
t = Table('t', m,
        Column('id', Integer, primary_key=True, autoincrement=False),
        Column('x', Integer))
m.create_all(engine)

Note

An INSERT statement which refers to an explicit value for such
a column is prohibited by SQL Server, however SQLAlchemy will detect this
and modify the <tt class="docutils literal">IDENTITY_INSERT</tt> flag accordingly at statement execution
time.  As this is not a high performing process, care should be taken to
set the <tt class="docutils literal">autoincrement</tt> flag appropriately for columns that will not
actually require IDENTITY behavior.

Controlling “Start” and “Increment”¶

Specific control over the parameters of the <tt class="docutils literal">IDENTITY</tt> value is supported
using the <tt class="xref py py-class docutils literal">schema.Sequence</tt> object.  While this object normally
represents an explicit “sequence” for supporting backends, on SQL Server it is
re-purposed to specify behavior regarding the identity column, including
support of the “start” and “increment” values:

from sqlalchemy import Table, Integer, Sequence, Column

Table('test', metadata,
       Column('id', Integer,
              Sequence('blah', start=100, increment=10),
              primary_key=True),
       Column('name', String(20))
     ).create(some_engine)

would yield:

CREATE TABLE test (
  id INTEGER NOT NULL IDENTITY(100,10) PRIMARY KEY,
  name VARCHAR(20) NULL,
  )

Note that the <tt class="docutils literal">start</tt> and <tt class="docutils literal">increment</tt> values for sequences are
optional and will default to 1,1.

INSERT behavior¶

Handling of the <tt class="docutils literal">IDENTITY</tt> column at INSERT time involves two key
techniques. The most common is being able to fetch the “last inserted value”
for a given <tt class="docutils literal">IDENTITY</tt> column, a process which SQLAlchemy performs
implicitly in many cases, most importantly within the ORM.

The process for fetching this value has several variants:

In the vast majority of cases, RETURNING is used in conjunction with INSERT
statements on SQL Server in order to get newly generated primary key values:

INSERT INTO t (x) OUTPUT inserted.id VALUES (?)

When RETURNING is not available or has been disabled via
<tt class="docutils literal">implicit_returning=False</tt>, either the <tt class="docutils literal">scope_identity()</tt> function or
the <tt class="docutils literal">@@identity</tt> variable is used; behavior varies by backend:

when using PyODBC, the phrase <tt class="docutils literal">; select scope_identity()</tt> will be
appended to the end of the INSERT statement; a second result set will be
fetched in order to receive the value.  Given a table as:

t = Table('t', m, Column('id', Integer, primary_key=True),
        Column('x', Integer),
        implicit_returning=False)

an INSERT will look like:

INSERT INTO t (x) VALUES (?); select scope_identity()

Other dialects such as pymssql will call upon
<tt class="docutils literal">SELECT scope_identity() AS lastrowid</tt> subsequent to an INSERT
statement. If the flag <tt class="docutils literal">use_scope_identity=False</tt> is passed to
<tt class="xref py py-func docutils literal">create_engine()</tt>, the statement <tt class="docutils literal">SELECT @@identity AS lastrowid</tt>
is used instead.

A table that contains an <tt class="docutils literal">IDENTITY</tt> column will prohibit an INSERT statement
that refers to the identity column explicitly.  The SQLAlchemy dialect will
detect when an INSERT construct, created using a core <tt class="xref py py-func docutils literal">insert()</tt>
construct (not a plain string SQL), refers to the identity column, and
in this case will emit <tt class="docutils literal">SET IDENTITY_INSERT ON</tt> prior to the insert
statement proceeding, and <tt class="docutils literal">SET IDENTITY_INSERT OFF</tt> subsequent to the
execution.  Given this example:

m = MetaData()
t = Table('t', m, Column('id', Integer, primary_key=True),
                Column('x', Integer))
m.create_all(engine)

engine.execute(t.insert(), {'id': 1, 'x':1}, {'id':2, 'x':2})

The above column will be created with IDENTITY, however the INSERT statement
we emit is specifying explicit values.  In the echo output we can see
how SQLAlchemy handles this:

CREATE TABLE t (
    id INTEGER NOT NULL IDENTITY(1,1),
    x INTEGER NULL,
    PRIMARY KEY (id)
)

COMMIT
SET IDENTITY_INSERT t ON
INSERT INTO t (id, x) VALUES (?, ?)
((1, 1), (2, 2))
SET IDENTITY_INSERT t OFF
COMMIT

This
is an auxilliary use case suitable for testing and bulk insert scenarios.

Collation Support¶

Character collations are supported by the base string types,
specified by the string argument “collation”:

from sqlalchemy import VARCHAR
Column('login', VARCHAR(32, collation='Latin1_General_CI_AS'))

When such a column is associated with a <tt class="xref py py-class docutils literal">Table</tt>, the
CREATE TABLE statement for this column will yield:

login VARCHAR(32) COLLATE Latin1_General_CI_AS NULL

New in version 0.8: Character collations are now part of the base string
types.

LIMIT/OFFSET Support¶

MSSQL has no support for the LIMIT or OFFSET keysowrds. LIMIT is
supported directly through the <tt class="docutils literal">TOP</tt> Transact SQL keyword:

select.limit

will yield:

SELECT TOP n

If using SQL Server 2005 or above, LIMIT with OFFSET
support is available through the <tt class="docutils literal">ROW_NUMBER OVER</tt> construct.
For versions below 2005, LIMIT with OFFSET usage will fail.

Nullability¶

MSSQL has support for three levels of column nullability. The default
nullability allows nulls and is explicit in the CREATE TABLE
construct:

name VARCHAR(20) NULL

If <tt class="docutils literal">nullable=None</tt> is specified then no specification is made. In
other words the database’s configured default is used. This will
render:

name VARCHAR(20)

If <tt class="docutils literal">nullable</tt> is <tt class="docutils literal">True</tt> or <tt class="docutils literal">False</tt> then the column will be
<tt class="docutils literal">NULL` or ``NOT NULL</tt> respectively.

Date / Time Handling¶

DATE and TIME are supported.   Bind parameters are converted
to datetime.datetime() objects as required by most MSSQL drivers,
and results are processed from strings if needed.
The DATE and TIME types are not available for MSSQL 2005 and
previous - if a server version below 2008 is detected, DDL
for these types will be issued as DATETIME.

Clustered Index Support¶

The MSSQL dialect supports clustered indexes (and primary keys) via the
<tt class="docutils literal">mssql_clustered</tt> option.  This option is available to <tt class="xref py py-class docutils literal">Index</tt>,
<tt class="xref py py-class docutils literal">UniqueConstraint</tt>. and <tt class="xref py py-class docutils literal">PrimaryKeyConstraint</tt>.

To generate a clustered index:

Index("my_index", table.c.x, mssql_clustered=True)

which renders the index as <tt class="docutils literal">CREATE CLUSTERED INDEX my_index ON table (x)</tt>.

New in version 0.8.

To generate a clustered primary key use:

Table('my_table', metadata,
      Column('x', ...),
      Column('y', ...),
      PrimaryKeyConstraint("x", "y", mssql_clustered=True))

which will render the table, for example, as:

CREATE TABLE my_table (x INTEGER NOT NULL, y INTEGER NOT NULL,
                       PRIMARY KEY CLUSTERED (x, y))

Similarly, we can generate a clustered unique constraint using:

  Table('my_table', metadata,
        Column('x', ...),
        Column('y', ...),
        PrimaryKeyConstraint("x"),
        UniqueConstraint("y", mssql_clustered=True),
        )

.. versionadded:: 0.9.2

MSSQL-Specific Index Options¶

In addition to clustering, the MSSQL dialect supports other special options
for <tt class="xref py py-class docutils literal">Index</tt>.

INCLUDE¶

The <tt class="docutils literal">mssql_include</tt> option renders INCLUDE(colname) for the given string
names:

Index("my_index", table.c.x, mssql_include=['y'])

would render the index as <tt class="docutils literal">CREATE INDEX my_index ON table (x) INCLUDE (y)</tt>

New in version 0.8.

Index ordering¶

Index ordering is available via functional expressions, such as:

Index("my_index", table.c.x.desc())

would render the index as <tt class="docutils literal">CREATE INDEX my_index ON table (x DESC)</tt>

New in version 0.8.

See also

Functional Indexes

Compatibility Levels¶

MSSQL supports the notion of setting compatibility levels at the
database level. This allows, for instance, to run a database that
is compatible with SQL2000 while running on a SQL2005 database
server. <tt class="docutils literal">server_version_info</tt> will always return the database
server version information (in this case SQL2005) and not the
compatibility level information. Because of this, if running under
a backwards compatibility mode SQAlchemy may attempt to use T-SQL
statements that are unable to be parsed by the database server.

Triggers¶

SQLAlchemy by default uses OUTPUT INSERTED to get at newly
generated primary key values via IDENTITY columns or other
server side defaults.   MS-SQL does not
allow the usage of OUTPUT INSERTED on tables that have triggers.
To disable the usage of OUTPUT INSERTED on a per-table basis,
specify <tt class="docutils literal">implicit_returning=False</tt> for each <tt class="xref py py-class docutils literal">Table</tt>
which has triggers:

Table('mytable', metadata,
    Column('id', Integer, primary_key=True),
    # ...,
    implicit_returning=False
)

Declarative form:

class MyClass(Base):
    # ...
    __table_args__ = {'implicit_returning':False}

This option can also be specified engine-wide using the
<tt class="docutils literal">implicit_returning=False</tt> argument on <tt class="xref py py-func docutils literal">create_engine()</tt>.

Enabling Snapshot Isolation¶

Not necessarily specific to SQLAlchemy, SQL Server has a default transaction
isolation mode that locks entire tables, and causes even mildly concurrent
applications to have long held locks and frequent deadlocks.
Enabling snapshot isolation for the database as a whole is recommended
for modern levels of concurrency support.  This is accomplished via the
following ALTER DATABASE commands executed at the SQL prompt:

ALTER DATABASE MyDatabase SET ALLOW_SNAPSHOT_ISOLATION ON

ALTER DATABASE MyDatabase SET READ_COMMITTED_SNAPSHOT ON

Background on SQL Server snapshot isolation is available at
http://msdn.microsoft.com/en-us/library/ms175095.aspx.

Known Issues¶

No support for more than one <tt class="docutils literal">IDENTITY</tt> column per table

reflection of indexes does not work with versions older than
SQL Server 2005

SQL Server Data Types¶

As with all SQLAlchemy dialects, all UPPERCASE types that are known to be
valid with SQL server are importable from the top level dialect, whether
they originate from <tt class="xref py py-mod docutils literal">sqlalchemy.types</tt> or from the local dialect:

from sqlalchemy.dialects.mssql import \
    BIGINT, BINARY, BIT, CHAR, DATE, DATETIME, DATETIME2, \
    DATETIMEOFFSET, DECIMAL, FLOAT, IMAGE, INTEGER, MONEY, \
    NCHAR, NTEXT, NUMERIC, NVARCHAR, REAL, SMALLDATETIME, \
    SMALLINT, SMALLMONEY, SQL_VARIANT, TEXT, TIME, \
    TIMESTAMP, TINYINT, UNIQUEIDENTIFIER, VARBINARY, VARCHAR

Types which are specific to SQL Server, or have SQL Server-specific
construction arguments, are as follows:

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">BIT</tt>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.TypeEngine</tt>

<tt class="descname">__init__</tt>¶

x.__init__(...) initializes x; see help(type(x)) for signature

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">CHAR</tt><big>(</big>length=None, collation=None, convert_unicode=False, unicode_error=None, _warn_on_bytestring=False<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.String</tt>

The SQL CHAR type.

<tt class="descname">__init__</tt><big>(</big>length=None, collation=None, convert_unicode=False, unicode_error=None, _warn_on_bytestring=False<big>)</big>¶

Create a string-holding type.

<col class="field-name" />
<col class="field-body" />

Parameters:

length¶ – optional, a length for the column for use in
DDL and CAST expressions.  May be safely omitted if no <tt class="docutils literal">CREATE
TABLE</tt> will be issued.  Certain databases may require a
<tt class="docutils literal">length</tt> for use in DDL, and will raise an exception when
the <tt class="docutils literal">CREATE TABLE</tt> DDL is issued if a <tt class="docutils literal">VARCHAR</tt>
with no length is included.  Whether the value is
interpreted as bytes or characters is database specific.

collation¶ –
Optional, a column-level collation for
use in DDL and CAST expressions.  Renders using the
COLLATE keyword supported by SQLite, MySQL, and Postgresql.
E.g.:

>>> from sqlalchemy import cast, select, String
>>> print select([cast('some string', String(collation='utf8'))])
SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1

New in version 0.8: Added support for COLLATE to all
string types.

convert_unicode¶ –
When set to <tt class="docutils literal">True</tt>, the
<tt class="xref py py-class docutils literal">String</tt> type will assume that
input is to be passed as Python <tt class="docutils literal">unicode</tt> objects,
and results returned as Python <tt class="docutils literal">unicode</tt> objects.
If the DBAPI in use does not support Python unicode
(which is fewer and fewer these days), SQLAlchemy
will encode/decode the value, using the
value of the <tt class="docutils literal">encoding</tt> parameter passed to
<tt class="xref py py-func docutils literal">create_engine()</tt> as the encoding.

When using a DBAPI that natively supports Python
unicode objects, this flag generally does not
need to be set.  For columns that are explicitly
intended to store non-ASCII data, the <tt class="xref py py-class docutils literal">Unicode</tt>
or <tt class="xref py py-class docutils literal">UnicodeText</tt>
types should be used regardless, which feature
the same behavior of <tt class="docutils literal">convert_unicode</tt> but
also indicate an underlying column type that
directly supports unicode, such as <tt class="docutils literal">NVARCHAR</tt>.

For the extremely rare case that Python <tt class="docutils literal">unicode</tt>
is to be encoded/decoded by SQLAlchemy on a backend
that does natively support Python <tt class="docutils literal">unicode</tt>,
the value <tt class="docutils literal">force</tt> can be passed here which will
cause SQLAlchemy’s encode/decode services to be
used unconditionally.

unicode_error¶ – Optional, a method to use to handle Unicode
conversion errors. Behaves like the <tt class="docutils literal">errors</tt> keyword argument to
the standard library’s <tt class="docutils literal">string.decode()</tt> functions.   This flag
requires that <tt class="docutils literal">convert_unicode</tt> is set to <tt class="docutils literal">force</tt> - otherwise,
SQLAlchemy is not guaranteed to handle the task of unicode
conversion.   Note that this flag adds significant performance
overhead to row-fetching operations for backends that already
return unicode objects natively (which most DBAPIs do).  This
flag should only be used as a last resort for reading
strings from a column with varied or corrupted encodings.

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">DATETIME2</tt><big>(</big>precision=None, **kw<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.dialects.mssql.base._DateTimeBase</tt>, <tt class="xref py py-class docutils literal">sqlalchemy.types.DateTime</tt>

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">DATETIMEOFFSET</tt><big>(</big>precision=None, **kwargs<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.TypeEngine</tt>

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">IMAGE</tt><big>(</big>length=None<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.LargeBinary</tt>

<tt class="descname">__init__</tt><big>(</big>length=None<big>)</big>¶

Construct a LargeBinary type.

<col class="field-name" />
<col class="field-body" />

Parameters:	length¶ – optional, a length for the column for use in
DDL statements, for those BLOB types that accept a length
(i.e. MySQL).  It does not produce a small BINARY/VARBINARY
type - use the BINARY/VARBINARY types specifically for those.
May be safely omitted if no <tt class="docutils literal">CREATE
TABLE</tt> will be issued.  Certain databases may require a
length for use in DDL, and will raise an exception when
the <tt class="docutils literal">CREATE TABLE</tt> DDL is issued.

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">MONEY</tt>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.TypeEngine</tt>

<tt class="descname">__init__</tt>¶

x.__init__(...) initializes x; see help(type(x)) for signature

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">NCHAR</tt><big>(</big>length=None, **kwargs<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.Unicode</tt>

The SQL NCHAR type.

<tt class="descname">__init__</tt><big>(</big>length=None, **kwargs<big>)</big>¶

Create a <tt class="xref py py-class docutils literal">Unicode</tt> object.

Parameters are the same as that of <tt class="xref py py-class docutils literal">String</tt>,
with the exception that <tt class="docutils literal">convert_unicode</tt>
defaults to <tt class="docutils literal">True</tt>.

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">NTEXT</tt><big>(</big>length=None, **kwargs<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.UnicodeText</tt>

MSSQL NTEXT type, for variable-length unicode text up to 2^30
characters.

<tt class="descname">__init__</tt><big>(</big>length=None, **kwargs<big>)</big>¶

Create a Unicode-converting Text type.

Parameters are the same as that of <tt class="xref py py-class docutils literal">Text</tt>,
with the exception that <tt class="docutils literal">convert_unicode</tt>
defaults to <tt class="docutils literal">True</tt>.

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">NVARCHAR</tt><big>(</big>length=None, **kwargs<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.Unicode</tt>

The SQL NVARCHAR type.

<tt class="descname">__init__</tt><big>(</big>length=None, **kwargs<big>)</big>¶

Create a <tt class="xref py py-class docutils literal">Unicode</tt> object.

Parameters are the same as that of <tt class="xref py py-class docutils literal">String</tt>,
with the exception that <tt class="docutils literal">convert_unicode</tt>
defaults to <tt class="docutils literal">True</tt>.

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">REAL</tt><big>(</big>**kw<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.REAL</tt>

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">SMALLDATETIME</tt><big>(</big>timezone=False<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.dialects.mssql.base._DateTimeBase</tt>, <tt class="xref py py-class docutils literal">sqlalchemy.types.DateTime</tt>

<tt class="descname">__init__</tt><big>(</big>timezone=False<big>)</big>¶

Construct a new <tt class="xref py py-class docutils literal">DateTime</tt>.

<col class="field-name" />
<col class="field-body" />

Parameters:	timezone¶ – boolean.  If True, and supported by the
backend, will produce ‘TIMESTAMP WITH TIMEZONE’. For backends
that don’t support timezone aware timestamps, has no
effect.

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">SMALLMONEY</tt>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.TypeEngine</tt>

<tt class="descname">__init__</tt>¶

x.__init__(...) initializes x; see help(type(x)) for signature

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">SQL_VARIANT</tt>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.TypeEngine</tt>

<tt class="descname">__init__</tt>¶

x.__init__(...) initializes x; see help(type(x)) for signature

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">TEXT</tt><big>(</big>length=None, collation=None, convert_unicode=False, unicode_error=None, _warn_on_bytestring=False<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.Text</tt>

The SQL TEXT type.

<tt class="descname">__init__</tt><big>(</big>length=None, collation=None, convert_unicode=False, unicode_error=None, _warn_on_bytestring=False<big>)</big>¶

Create a string-holding type.

<col class="field-name" />
<col class="field-body" />

Parameters:

length¶ – optional, a length for the column for use in
DDL and CAST expressions.  May be safely omitted if no <tt class="docutils literal">CREATE
TABLE</tt> will be issued.  Certain databases may require a
<tt class="docutils literal">length</tt> for use in DDL, and will raise an exception when
the <tt class="docutils literal">CREATE TABLE</tt> DDL is issued if a <tt class="docutils literal">VARCHAR</tt>
with no length is included.  Whether the value is
interpreted as bytes or characters is database specific.

collation¶ –
Optional, a column-level collation for
use in DDL and CAST expressions.  Renders using the
COLLATE keyword supported by SQLite, MySQL, and Postgresql.
E.g.:

>>> from sqlalchemy import cast, select, String
>>> print select([cast('some string', String(collation='utf8'))])
SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1

New in version 0.8: Added support for COLLATE to all
string types.

convert_unicode¶ –
When set to <tt class="docutils literal">True</tt>, the
<tt class="xref py py-class docutils literal">String</tt> type will assume that
input is to be passed as Python <tt class="docutils literal">unicode</tt> objects,
and results returned as Python <tt class="docutils literal">unicode</tt> objects.
If the DBAPI in use does not support Python unicode
(which is fewer and fewer these days), SQLAlchemy
will encode/decode the value, using the
value of the <tt class="docutils literal">encoding</tt> parameter passed to
<tt class="xref py py-func docutils literal">create_engine()</tt> as the encoding.

When using a DBAPI that natively supports Python
unicode objects, this flag generally does not
need to be set.  For columns that are explicitly
intended to store non-ASCII data, the <tt class="xref py py-class docutils literal">Unicode</tt>
or <tt class="xref py py-class docutils literal">UnicodeText</tt>
types should be used regardless, which feature
the same behavior of <tt class="docutils literal">convert_unicode</tt> but
also indicate an underlying column type that
directly supports unicode, such as <tt class="docutils literal">NVARCHAR</tt>.

For the extremely rare case that Python <tt class="docutils literal">unicode</tt>
is to be encoded/decoded by SQLAlchemy on a backend
that does natively support Python <tt class="docutils literal">unicode</tt>,
the value <tt class="docutils literal">force</tt> can be passed here which will
cause SQLAlchemy’s encode/decode services to be
used unconditionally.

unicode_error¶ – Optional, a method to use to handle Unicode
conversion errors. Behaves like the <tt class="docutils literal">errors</tt> keyword argument to
the standard library’s <tt class="docutils literal">string.decode()</tt> functions.   This flag
requires that <tt class="docutils literal">convert_unicode</tt> is set to <tt class="docutils literal">force</tt> - otherwise,
SQLAlchemy is not guaranteed to handle the task of unicode
conversion.   Note that this flag adds significant performance
overhead to row-fetching operations for backends that already
return unicode objects natively (which most DBAPIs do).  This
flag should only be used as a last resort for reading
strings from a column with varied or corrupted encodings.

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">TIME</tt><big>(</big>precision=None, **kwargs<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.TIME</tt>

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">TINYINT</tt>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.Integer</tt>

<tt class="descname">__init__</tt>¶

x.__init__(...) initializes x; see help(type(x)) for signature

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">UNIQUEIDENTIFIER</tt>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.TypeEngine</tt>

<tt class="descname">__init__</tt>¶

x.__init__(...) initializes x; see help(type(x)) for signature

class <tt class="descclassname">sqlalchemy.dialects.mssql.</tt><tt class="descname">VARCHAR</tt><big>(</big>length=None, collation=None, convert_unicode=False, unicode_error=None, _warn_on_bytestring=False<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">sqlalchemy.types.String</tt>

The SQL VARCHAR type.

<tt class="descname">__init__</tt><big>(</big>length=None, collation=None, convert_unicode=False, unicode_error=None, _warn_on_bytestring=False<big>)</big>¶

Create a string-holding type.

<col class="field-name" />
<col class="field-body" />

Parameters:

length¶ – optional, a length for the column for use in
DDL and CAST expressions.  May be safely omitted if no <tt class="docutils literal">CREATE
TABLE</tt> will be issued.  Certain databases may require a
<tt class="docutils literal">length</tt> for use in DDL, and will raise an exception when
the <tt class="docutils literal">CREATE TABLE</tt> DDL is issued if a <tt class="docutils literal">VARCHAR</tt>
with no length is included.  Whether the value is
interpreted as bytes or characters is database specific.

collation¶ –
Optional, a column-level collation for
use in DDL and CAST expressions.  Renders using the
COLLATE keyword supported by SQLite, MySQL, and Postgresql.
E.g.:

>>> from sqlalchemy import cast, select, String
>>> print select([cast('some string', String(collation='utf8'))])
SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1

New in version 0.8: Added support for COLLATE to all
string types.

convert_unicode¶ –
When set to <tt class="docutils literal">True</tt>, the
<tt class="xref py py-class docutils literal">String</tt> type will assume that
input is to be passed as Python <tt class="docutils literal">unicode</tt> objects,
and results returned as Python <tt class="docutils literal">unicode</tt> objects.
If the DBAPI in use does not support Python unicode
(which is fewer and fewer these days), SQLAlchemy
will encode/decode the value, using the
value of the <tt class="docutils literal">encoding</tt> parameter passed to
<tt class="xref py py-func docutils literal">create_engine()</tt> as the encoding.

When using a DBAPI that natively supports Python
unicode objects, this flag generally does not
need to be set.  For columns that are explicitly
intended to store non-ASCII data, the <tt class="xref py py-class docutils literal">Unicode</tt>
or <tt class="xref py py-class docutils literal">UnicodeText</tt>
types should be used regardless, which feature
the same behavior of <tt class="docutils literal">convert_unicode</tt> but
also indicate an underlying column type that
directly supports unicode, such as <tt class="docutils literal">NVARCHAR</tt>.

For the extremely rare case that Python <tt class="docutils literal">unicode</tt>
is to be encoded/decoded by SQLAlchemy on a backend
that does natively support Python <tt class="docutils literal">unicode</tt>,
the value <tt class="docutils literal">force</tt> can be passed here which will
cause SQLAlchemy’s encode/decode services to be
used unconditionally.

unicode_error¶ – Optional, a method to use to handle Unicode
conversion errors. Behaves like the <tt class="docutils literal">errors</tt> keyword argument to
the standard library’s <tt class="docutils literal">string.decode()</tt> functions.   This flag
requires that <tt class="docutils literal">convert_unicode</tt> is set to <tt class="docutils literal">force</tt> - otherwise,
SQLAlchemy is not guaranteed to handle the task of unicode
conversion.   Note that this flag adds significant performance
overhead to row-fetching operations for backends that already
return unicode objects natively (which most DBAPIs do).  This
flag should only be used as a last resort for reading
strings from a column with varied or corrupted encodings.

PyODBC¶

Support for the Microsoft SQL Server database via the PyODBC driver.

DBAPI¶

Documentation and download information (if applicable) for PyODBC is available at:
http://pypi.python.org/pypi/pyodbc/

Connecting¶

Connect String:

mssql+pyodbc://<username>:<password>@<dsnname>

Additional Connection Examples¶

Examples of pyodbc connection string URLs:

<tt class="docutils literal">mssql+pyodbc://mydsn</tt> - connects using the specified DSN named <tt class="docutils literal">mydsn</tt>.
The connection string that is created will appear like:

dsn=mydsn;Trusted_Connection=Yes

<tt class="docutils literal">mssql+pyodbc://user:pass@mydsn</tt> - connects using the DSN named
<tt class="docutils literal">mydsn</tt> passing in the <tt class="docutils literal">UID</tt> and <tt class="docutils literal">PWD</tt> information. The
connection string that is created will appear like:

dsn=mydsn;UID=user;PWD=pass

<tt class="docutils literal">mssql+pyodbc://user:pass@mydsn/?LANGUAGE=us_english</tt> - connects
using the DSN named <tt class="docutils literal">mydsn</tt> passing in the <tt class="docutils literal">UID</tt> and <tt class="docutils literal">PWD</tt>
information, plus the additional connection configuration option
<tt class="docutils literal">LANGUAGE</tt>. The connection string that is created will appear
like:

dsn=mydsn;UID=user;PWD=pass;LANGUAGE=us_english

<tt class="docutils literal">mssql+pyodbc://user:pass@host/db</tt> - connects using a connection
that would appear like:

DRIVER={SQL Server};Server=host;Database=db;UID=user;PWD=pass

<tt class="docutils literal">mssql+pyodbc://user:pass@host:123/db</tt> - connects using a connection
string which includes the port
information using the comma syntax. This will create the following
connection string:

DRIVER={SQL Server};Server=host,123;Database=db;UID=user;PWD=pass

<tt class="docutils literal">mssql+pyodbc://user:pass@host/db?port=123</tt> - connects using a connection
string that includes the port
information as a separate <tt class="docutils literal">port</tt> keyword. This will create the
following connection string:

DRIVER={SQL Server};Server=host;Database=db;UID=user;PWD=pass;port=123

<tt class="docutils literal">mssql+pyodbc://user:pass@host/db?driver=MyDriver</tt> - connects using a
connection string that includes a custom ODBC driver name.  This will create
the following connection string:

DRIVER={MyDriver};Server=host;Database=db;UID=user;PWD=pass

If you require a connection string that is outside the options
presented above, use the <tt class="docutils literal">odbc_connect</tt> keyword to pass in a
urlencoded connection string. What gets passed in will be urldecoded
and passed directly.

For example:

mssql+pyodbc:///?odbc_connect=dsn%3Dmydsn%3BDatabase%3Ddb

would create the following connection string:

dsn=mydsn;Database=db

Encoding your connection string can be easily accomplished through
the python shell. For example:

>>> import urllib
>>> urllib.quote_plus('dsn=mydsn;Database=db')
'dsn%3Dmydsn%3BDatabase%3Ddb'

Unicode Binds¶

The current state of PyODBC on a unix backend with FreeTDS and/or
EasySoft is poor regarding unicode; different OS platforms and versions of
UnixODBC versus IODBC versus FreeTDS/EasySoft versus PyODBC itself
dramatically alter how strings are received.  The PyODBC dialect attempts to
use all the information it knows to determine whether or not a Python unicode
literal can be passed directly to the PyODBC driver or not; while SQLAlchemy
can encode these to bytestrings first, some users have reported that PyODBC
mis-handles bytestrings for certain encodings and requires a Python unicode
object, while the author has observed widespread cases where a Python unicode
is completely misinterpreted by PyODBC, particularly when dealing with
the information schema tables used in table reflection, and the value
must first be encoded to a bytestring.

It is for this reason that whether or not unicode literals for bound
parameters be sent to PyODBC can be controlled using the
<tt class="docutils literal">supports_unicode_binds</tt> parameter to <tt class="docutils literal">create_engine()</tt>.  When
left at its default of <tt class="docutils literal">None</tt>, the PyODBC dialect will use its
best guess as to whether or not the driver deals with unicode literals
well.  When <tt class="docutils literal">False</tt>, unicode literals will be encoded first, and when
<tt class="docutils literal">True</tt> unicode literals will be passed straight through.  This is an interim
flag that hopefully should not be needed when the unicode situation stabilizes
for unix + PyODBC.

New in version 0.7.7: <tt class="docutils literal">supports_unicode_binds</tt> parameter to <tt class="docutils literal">create_engine()</tt>.

mxODBC¶

Support for the Microsoft SQL Server database via the mxODBC driver.

DBAPI¶

Documentation and download information (if applicable) for mxODBC is available at:
http://www.egenix.com/

Connecting¶

Connect String:

mssql+mxodbc://<username>:<password>@<dsnname>

Execution Modes¶

mxODBC features two styles of statement execution, using the
<tt class="docutils literal">cursor.execute()</tt> and <tt class="docutils literal">cursor.executedirect()</tt> methods (the second being
an extension to the DBAPI specification). The former makes use of a particular
API call specific to the SQL Server Native Client ODBC driver known
SQLDescribeParam, while the latter does not.

mxODBC apparently only makes repeated use of a single prepared statement
when SQLDescribeParam is used. The advantage to prepared statement reuse is
one of performance. The disadvantage is that SQLDescribeParam has a limited
set of scenarios in which bind parameters are understood, including that they
cannot be placed within the argument lists of function calls, anywhere outside
the FROM, or even within subqueries within the FROM clause - making the usage
of bind parameters within SELECT statements impossible for all but the most
simplistic statements.

For this reason, the mxODBC dialect uses the “native” mode by default only for
INSERT, UPDATE, and DELETE statements, and uses the escaped string mode for
all other statements.

This behavior can be controlled via
<tt class="xref py py-meth docutils literal">execution_options()</tt> using the
<tt class="docutils literal">native_odbc_execute</tt> flag with a value of <tt class="docutils literal">True</tt> or <tt class="docutils literal">False</tt>, where a
value of <tt class="docutils literal">True</tt> will unconditionally use native bind parameters and a value
of <tt class="docutils literal">False</tt> will unconditionally use string-escaped parameters.

pymssql¶

Support for the Microsoft SQL Server database via the pymssql driver.

DBAPI¶

Documentation and download information (if applicable) for pymssql is available at:
http://pymssql.org/

Connecting¶

Connect String:

mssql+pymssql://<username>:<password>@<freetds_name>?charset=utf8

pymssql is a Python module that provides a Python DBAPI interface around
FreeTDS.  Compatible builds are available for
Linux, MacOSX and Windows platforms.

zxjdbc¶

Support for the Microsoft SQL Server database via the zxJDBC for Jython driver.

DBAPI¶

Drivers for this database are available at:
http://jtds.sourceforge.net/

Connecting¶

Connect String:

mssql+zxjdbc://user:pass@host:port/dbname[?key=value&key=value...]

AdoDBAPI¶

Support for the Microsoft SQL Server database via the adodbapi driver.

DBAPI¶

Documentation and download information (if applicable) for adodbapi is available at:
http://adodbapi.sourceforge.net/

Connecting¶

Connect String:

mssql+adodbapi://<username>:<password>@<dsnname>

Note

The adodbapi dialect is not implemented SQLAlchemy versions 0.6 and
above at this time.

        Previous:
        Firebird
        Next:
        MySQL

        © Copyright 2007-2015, the SQLAlchemy authors and contributors.
        Created using Sphinx 1.2.3.


text:
import Resource from 'koa-resource-router'
import db from 'src/server/db'

const Promotion = db.promotions

export default new Resource('promotions', {
  // GET /cpromotions
  index: function *(next) {
    this.body = yield Promotion.fetchPair()
  }
})


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2014-2019 The DigiByte Core developers
// Copyright (c) 2014-2019 The Auroracoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef AURORACOIN_WARNINGS_H
#define AURORACOIN_WARNINGS_H

#include <stdlib.h>
#include <string>

void SetMiscWarning(const std::string& strWarning);
void SetfLargeWorkForkFound(bool flag);
bool GetfLargeWorkForkFound();
void SetfLargeWorkInvalidChainFound(bool flag);
/** Format a string that describes several potential problems detected by the core.
 * @param[in] strFor can have the following values:
 * - "statusbar": get the most important warning
 * - "gui": get all warnings, translated (where possible) for GUI, separated by <hr />
 * @returns the warning string selected by strFor
 */
std::string GetWarnings(const std::string& strFor);

#endif //  AURORACOIN_WARNINGS_H


text:
@protocol NativeSourcesProtocol <NSObject>

- (NSUInteger)scriptCount;
- (NSUInteger)indexOfScript:(NSString *)name;
- (NSString *)nameOfScriptAtIndex:(NSUInteger)index;
- (NSString *)nameOfModuleAtIndex:(NSUInteger)index;
- (NSString *)sourceOfScriptAtIndex:(NSUInteger)index;

@end

@interface NativeSources : NSObject <NativeSourcesProtocol>

+ (id<NativeSourcesProtocol>)sourcesWithUrl:(NSURL *)url error:(NSError **)error;

@end

NSString * const CoreNodeScriptName;
NSString * const CoreNodeIOSScriptName;


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.GraphQLNonNull = exports.GraphQLList = exports.GraphQLInputObjectType = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLObjectType = exports.GraphQLScalarType = undefined;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

exports.isType = isType;
exports.assertType = assertType;
exports.isInputType = isInputType;
exports.assertInputType = assertInputType;
exports.isOutputType = isOutputType;
exports.assertOutputType = assertOutputType;
exports.isLeafType = isLeafType;
exports.assertLeafType = assertLeafType;
exports.isCompositeType = isCompositeType;
exports.assertCompositeType = assertCompositeType;
exports.isAbstractType = isAbstractType;
exports.assertAbstractType = assertAbstractType;
exports.getNullableType = getNullableType;
exports.getNamedType = getNamedType;

var _invariant = require('../jsutils/invariant');

var _invariant2 = _interopRequireDefault(_invariant);

var _isNullish = require('../jsutils/isNullish');

var _isNullish2 = _interopRequireDefault(_isNullish);

var _kinds = require('../language/kinds');

var _assertValidName = require('../utilities/assertValidName');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

// Predicates & Assertions

/**
 * These are all of the possible kinds of types.
 */
function isType(type) {
  return type instanceof GraphQLScalarType || type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType || type instanceof GraphQLEnumType || type instanceof GraphQLInputObjectType || type instanceof GraphQLList || type instanceof GraphQLNonNull;
}

function assertType(type) {
  (0, _invariant2.default)(isType(type), 'Expected ' + String(type) + ' to be a GraphQL type.');
  return type;
}

/**
 * These types may be used as input types for arguments and directives.
 */
function isInputType(type) {
  var namedType = getNamedType(type);
  return namedType instanceof GraphQLScalarType || namedType instanceof GraphQLEnumType || namedType instanceof GraphQLInputObjectType;
}

function assertInputType(type) {
  (0, _invariant2.default)(isInputType(type), 'Expected ' + String(type) + ' to be a GraphQL input type.');
  return type;
}

/**
 * These types may be used as output types as the result of fields.
 */
function isOutputType(type) {
  var namedType = getNamedType(type);
  return namedType instanceof GraphQLScalarType || namedType instanceof GraphQLObjectType || namedType instanceof GraphQLInterfaceType || namedType instanceof GraphQLUnionType || namedType instanceof GraphQLEnumType;
}

function assertOutputType(type) {
  (0, _invariant2.default)(isOutputType(type), 'Expected ' + String(type) + ' to be a GraphQL output type.');
  return type;
}

/**
 * These types may describe types which may be leaf values.
 */
function isLeafType(type) {
  var namedType = getNamedType(type);
  return namedType instanceof GraphQLScalarType || namedType instanceof GraphQLEnumType;
}

function assertLeafType(type) {
  (0, _invariant2.default)(isLeafType(type), 'Expected ' + String(type) + ' to be a GraphQL leaf type.');
  return type;
}

/**
 * These types may describe the parent context of a selection set.
 */
function isCompositeType(type) {
  return type instanceof GraphQLObjectType || type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType;
}

function assertCompositeType(type) {
  (0, _invariant2.default)(isCompositeType(type), 'Expected ' + String(type) + ' to be a GraphQL composite type.');
  return type;
}

/**
 * These types may describe the parent context of a selection set.
 */
function isAbstractType(type) {
  return type instanceof GraphQLInterfaceType || type instanceof GraphQLUnionType;
}

function assertAbstractType(type) {
  (0, _invariant2.default)(isAbstractType(type), 'Expected ' + String(type) + ' to be a GraphQL abstract type.');
  return type;
}

/**
 * These types can all accept null as a value.
 */
function getNullableType(type) {
  return type instanceof GraphQLNonNull ? type.ofType : type;
}

/**
 * These named types do not include modifiers like List or NonNull.
 */
function getNamedType(type) {
  var unmodifiedType = type;
  while (unmodifiedType instanceof GraphQLList || unmodifiedType instanceof GraphQLNonNull) {
    unmodifiedType = unmodifiedType.ofType;
  }
  return unmodifiedType;
}

/**
 * Used while defining GraphQL types to allow for circular references in
 * otherwise immutable type definitions.
 */

function resolveThunk(thunk) {
  return typeof thunk === 'function' ? thunk() : thunk;
}

/**
 * Scalar Type Definition
 *
 * The leaf values of any request and input values to arguments are
 * Scalars (or Enums) and are defined with a name and a series of functions
 * used to parse input from ast or variables and to ensure validity.
 *
 * Example:
 *
 *     const OddType = new GraphQLScalarType({
 *       name: 'Odd',
 *       serialize(value) {
 *         return value % 2 === 1 ? value : null;
 *       }
 *     });
 *
 */

var GraphQLScalarType = exports.GraphQLScalarType = function () {
  function GraphQLScalarType(config) {
    _classCallCheck(this, GraphQLScalarType);

    (0, _invariant2.default)(config.name, 'Type must be named.');
    (0, _assertValidName.assertValidName)(config.name);
    this.name = config.name;
    this.description = config.description;
    (0, _invariant2.default)(typeof config.serialize === 'function', this.name + ' must provide "serialize" function. If this custom Scalar ' + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.');
    if (config.parseValue || config.parseLiteral) {
      (0, _invariant2.default)(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function', this.name + ' must provide both "parseValue" and "parseLiteral" ' + 'functions.');
    }
    this._scalarConfig = config;
  }

  // Serializes an internal value to include in a response.

  GraphQLScalarType.prototype.serialize = function serialize(value) {
    var serializer = this._scalarConfig.serialize;
    return serializer(value);
  };

  // Parses an externally provided value to use as an input.

  GraphQLScalarType.prototype.parseValue = function parseValue(value) {
    var parser = this._scalarConfig.parseValue;
    return parser ? parser(value) : null;
  };

  // Parses an externally provided literal value to use as an input.

  GraphQLScalarType.prototype.parseLiteral = function parseLiteral(valueNode) {
    var parser = this._scalarConfig.parseLiteral;
    return parser ? parser(valueNode) : null;
  };

  GraphQLScalarType.prototype.toString = function toString() {
    return this.name;
  };

  return GraphQLScalarType;
}();

// Also provide toJSON and inspect aliases for toString.

GraphQLScalarType.prototype.toJSON = GraphQLScalarType.prototype.inspect = GraphQLScalarType.prototype.toString;

/**
 * Object Type Definition
 *
 * Almost all of the GraphQL types you define will be object types. Object types
 * have a name, but most importantly describe their fields.
 *
 * Example:
 *
 *     const AddressType = new GraphQLObjectType({
 *       name: 'Address',
 *       fields: {
 *         street: { type: GraphQLString },
 *         number: { type: GraphQLInt },
 *         formatted: {
 *           type: GraphQLString,
 *           resolve(obj) {
 *             return obj.number + ' ' + obj.street
 *           }
 *         }
 *       }
 *     });
 *
 * When two types need to refer to each other, or a type needs to refer to
 * itself in a field, you can use a function expression (aka a closure or a
 * thunk) to supply the fields lazily.
 *
 * Example:
 *
 *     const PersonType = new GraphQLObjectType({
 *       name: 'Person',
 *       fields: () => ({
 *         name: { type: GraphQLString },
 *         bestFriend: { type: PersonType },
 *       })
 *     });
 *
 */
var GraphQLObjectType = exports.GraphQLObjectType = function () {
  function GraphQLObjectType(config) {
    _classCallCheck(this, GraphQLObjectType);

    (0, _invariant2.default)(config.name, 'Type must be named.');
    (0, _assertValidName.assertValidName)(config.name);
    this.name = config.name;
    this.description = config.description;
    if (config.isTypeOf) {
      (0, _invariant2.default)(typeof config.isTypeOf === 'function', this.name + ' must provide "isTypeOf" as a function.');
    }
    this.isTypeOf = config.isTypeOf;
    this._typeConfig = config;
  }

  GraphQLObjectType.prototype.getFields = function getFields() {
    return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields));
  };

  GraphQLObjectType.prototype.getInterfaces = function getInterfaces() {
    return this._interfaces || (this._interfaces = defineInterfaces(this, this._typeConfig.interfaces));
  };

  GraphQLObjectType.prototype.toString = function toString() {
    return this.name;
  };

  return GraphQLObjectType;
}();

// Also provide toJSON and inspect aliases for toString.

GraphQLObjectType.prototype.toJSON = GraphQLObjectType.prototype.inspect = GraphQLObjectType.prototype.toString;

function defineInterfaces(type, interfacesThunk) {
  var interfaces = resolveThunk(interfacesThunk);
  if (!interfaces) {
    return [];
  }
  (0, _invariant2.default)(Array.isArray(interfaces), type.name + ' interfaces must be an Array or a function which returns ' + 'an Array.');
  interfaces.forEach(function (iface) {
    (0, _invariant2.default)(iface instanceof GraphQLInterfaceType, type.name + ' may only implement Interface types, it cannot ' + ('implement: ' + String(iface) + '.'));
    if (typeof iface.resolveType !== 'function') {
      (0, _invariant2.default)(typeof type.isTypeOf === 'function', 'Interface Type ' + iface.name + ' does not provide a "resolveType" ' + ('function and implementing Type ' + type.name + ' does not provide a ') + '"isTypeOf" function. There is no way to resolve this implementing ' + 'type during execution.');
    }
  });
  return interfaces;
}

function defineFieldMap(type, fieldsThunk) {
  var fieldMap = resolveThunk(fieldsThunk);
  (0, _invariant2.default)(isPlainObj(fieldMap), type.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');

  var fieldNames = Object.keys(fieldMap);
  (0, _invariant2.default)(fieldNames.length > 0, type.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');

  var resultFieldMap = {};
  fieldNames.forEach(function (fieldName) {
    (0, _assertValidName.assertValidName)(fieldName);
    var fieldConfig = fieldMap[fieldName];
    (0, _invariant2.default)(!fieldConfig.hasOwnProperty('isDeprecated'), type.name + '.' + fieldName + ' should provide "deprecationReason" instead ' + 'of "isDeprecated".');
    var field = _extends({}, fieldConfig, {
      isDeprecated: Boolean(fieldConfig.deprecationReason),
      name: fieldName
    });
    (0, _invariant2.default)(isOutputType(field.type), type.name + '.' + fieldName + ' field type must be Output Type but ' + ('got: ' + String(field.type) + '.'));
    var argsConfig = fieldConfig.args;
    if (!argsConfig) {
      field.args = [];
    } else {
      (0, _invariant2.default)(isPlainObj(argsConfig), type.name + '.' + fieldName + ' args must be an object with argument ' + 'names as keys.');
      field.args = Object.keys(argsConfig).map(function (argName) {
        (0, _assertValidName.assertValidName)(argName);
        var arg = argsConfig[argName];
        (0, _invariant2.default)(isInputType(arg.type), type.name + '.' + fieldName + '(' + argName + ':) argument type must be ' + ('Input Type but got: ' + String(arg.type) + '.'));
        return {
          name: argName,
          description: arg.description === undefined ? null : arg.description,
          type: arg.type,
          defaultValue: arg.defaultValue
        };
      });
    }
    resultFieldMap[fieldName] = field;
  });
  return resultFieldMap;
}

function isPlainObj(obj) {
  return obj && typeof obj === 'object' && !Array.isArray(obj);
}

/**
 * Interface Type Definition
 *
 * When a field can return one of a heterogeneous set of types, a Interface type
 * is used to describe what types are possible, what fields are in common across
 * all types, as well as a function to determine which type is actually used
 * when the field is resolved.
 *
 * Example:
 *
 *     const EntityType = new GraphQLInterfaceType({
 *       name: 'Entity',
 *       fields: {
 *         name: { type: GraphQLString }
 *       }
 *     });
 *
 */
var GraphQLInterfaceType = exports.GraphQLInterfaceType = function () {
  function GraphQLInterfaceType(config) {
    _classCallCheck(this, GraphQLInterfaceType);

    (0, _invariant2.default)(config.name, 'Type must be named.');
    (0, _assertValidName.assertValidName)(config.name);
    this.name = config.name;
    this.description = config.description;
    if (config.resolveType) {
      (0, _invariant2.default)(typeof config.resolveType === 'function', this.name + ' must provide "resolveType" as a function.');
    }
    this.resolveType = config.resolveType;
    this._typeConfig = config;
  }

  GraphQLInterfaceType.prototype.getFields = function getFields() {
    return this._fields || (this._fields = defineFieldMap(this, this._typeConfig.fields));
  };

  GraphQLInterfaceType.prototype.toString = function toString() {
    return this.name;
  };

  return GraphQLInterfaceType;
}();

// Also provide toJSON and inspect aliases for toString.

GraphQLInterfaceType.prototype.toJSON = GraphQLInterfaceType.prototype.inspect = GraphQLInterfaceType.prototype.toString;

/**
 * Union Type Definition
 *
 * When a field can return one of a heterogeneous set of types, a Union type
 * is used to describe what types are possible as well as providing a function
 * to determine which type is actually used when the field is resolved.
 *
 * Example:
 *
 *     const PetType = new GraphQLUnionType({
 *       name: 'Pet',
 *       types: [ DogType, CatType ],
 *       resolveType(value) {
 *         if (value instanceof Dog) {
 *           return DogType;
 *         }
 *         if (value instanceof Cat) {
 *           return CatType;
 *         }
 *       }
 *     });
 *
 */
var GraphQLUnionType = exports.GraphQLUnionType = function () {
  function GraphQLUnionType(config) {
    _classCallCheck(this, GraphQLUnionType);

    (0, _invariant2.default)(config.name, 'Type must be named.');
    (0, _assertValidName.assertValidName)(config.name);
    this.name = config.name;
    this.description = config.description;
    if (config.resolveType) {
      (0, _invariant2.default)(typeof config.resolveType === 'function', this.name + ' must provide "resolveType" as a function.');
    }
    this.resolveType = config.resolveType;
    this._typeConfig = config;
  }

  GraphQLUnionType.prototype.getTypes = function getTypes() {
    return this._types || (this._types = defineTypes(this, this._typeConfig.types));
  };

  GraphQLUnionType.prototype.toString = function toString() {
    return this.name;
  };

  return GraphQLUnionType;
}();

// Also provide toJSON and inspect aliases for toString.

GraphQLUnionType.prototype.toJSON = GraphQLUnionType.prototype.inspect = GraphQLUnionType.prototype.toString;

function defineTypes(unionType, typesThunk) {
  var types = resolveThunk(typesThunk);

  (0, _invariant2.default)(Array.isArray(types) && types.length > 0, 'Must provide Array of types or a function which returns ' + ('such an array for Union ' + unionType.name + '.'));
  types.forEach(function (objType) {
    (0, _invariant2.default)(objType instanceof GraphQLObjectType, unionType.name + ' may only contain Object types, it cannot contain: ' + (String(objType) + '.'));
    if (typeof unionType.resolveType !== 'function') {
      (0, _invariant2.default)(typeof objType.isTypeOf === 'function', 'Union type "' + unionType.name + '" does not provide a "resolveType" ' + ('function and possible type "' + objType.name + '" does not provide an ') + '"isTypeOf" function. There is no way to resolve this possible type ' + 'during execution.');
    }
  });

  return types;
}

/**
 * Enum Type Definition
 *
 * Some leaf values of requests and input values are Enums. GraphQL serializes
 * Enum values as strings, however internally Enums can be represented by any
 * kind of type, often integers.
 *
 * Example:
 *
 *     const RGBType = new GraphQLEnumType({
 *       name: 'RGB',
 *       values: {
 *         RED: { value: 0 },
 *         GREEN: { value: 1 },
 *         BLUE: { value: 2 }
 *       }
 *     });
 *
 * Note: If a value is not provided in a definition, the name of the enum value
 * will be used as its internal value.
 */
var GraphQLEnumType /* <T> */ = exports.GraphQLEnumType = function () {
  function GraphQLEnumType(config /* <T> */) {
    _classCallCheck(this, GraphQLEnumType);

    this.name = config.name;
    (0, _assertValidName.assertValidName)(config.name);
    this.description = config.description;
    this._values = defineEnumValues(this, config.values);
    this._enumConfig = config;
  }

  GraphQLEnumType.prototype.getValues = function getValues() {
    return this._values;
  };

  GraphQLEnumType.prototype.serialize = function serialize(value /* T */) {
    var enumValue = this._getValueLookup().get(value);
    return enumValue ? enumValue.name : null;
  };

  GraphQLEnumType.prototype.parseValue = function parseValue(value) /* T */{
    if (typeof value === 'string') {
      var enumValue = this._getNameLookup()[value];
      if (enumValue) {
        return enumValue.value;
      }
    }
  };

  GraphQLEnumType.prototype.parseLiteral = function parseLiteral(valueNode) /* T */{
    if (valueNode.kind === _kinds.ENUM) {
      var enumValue = this._getNameLookup()[valueNode.value];
      if (enumValue) {
        return enumValue.value;
      }
    }
  };

  GraphQLEnumType.prototype._getValueLookup = function _getValueLookup() {
    var _this = this;

    if (!this._valueLookup) {
      (function () {
        var lookup = new Map();
        _this.getValues().forEach(function (value) {
          lookup.set(value.value, value);
        });
        _this._valueLookup = lookup;
      })();
    }
    return this._valueLookup;
  };

  GraphQLEnumType.prototype._getNameLookup = function _getNameLookup() {
    var _this2 = this;

    if (!this._nameLookup) {
      (function () {
        var lookup = Object.create(null);
        _this2.getValues().forEach(function (value) {
          lookup[value.name] = value;
        });
        _this2._nameLookup = lookup;
      })();
    }
    return this._nameLookup;
  };

  GraphQLEnumType.prototype.toString = function toString() {
    return this.name;
  };

  return GraphQLEnumType;
}();

// Also provide toJSON and inspect aliases for toString.

GraphQLEnumType.prototype.toJSON = GraphQLEnumType.prototype.inspect = GraphQLEnumType.prototype.toString;

function defineEnumValues(type, valueMap /* <T> */
) {
  (0, _invariant2.default)(isPlainObj(valueMap), type.name + ' values must be an object with value names as keys.');
  var valueNames = Object.keys(valueMap);
  (0, _invariant2.default)(valueNames.length > 0, type.name + ' values must be an object with value names as keys.');
  return valueNames.map(function (valueName) {
    (0, _assertValidName.assertValidName)(valueName);
    var value = valueMap[valueName];
    (0, _invariant2.default)(isPlainObj(value), type.name + '.' + valueName + ' must refer to an object with a "value" key ' + ('representing an internal value but got: ' + String(value) + '.'));
    (0, _invariant2.default)(!value.hasOwnProperty('isDeprecated'), type.name + '.' + valueName + ' should provide "deprecationReason" instead ' + 'of "isDeprecated".');
    return {
      name: valueName,
      description: value.description,
      isDeprecated: Boolean(value.deprecationReason),
      deprecationReason: value.deprecationReason,
      value: (0, _isNullish2.default)(value.value) ? valueName : value.value
    };
  });
} /* <T> */

/**
 * Input Object Type Definition
 *
 * An input object defines a structured collection of fields which may be
 * supplied to a field argument.
 *
 * Using `NonNull` will ensure that a value must be provided by the query
 *
 * Example:
 *
 *     const GeoPoint = new GraphQLInputObjectType({
 *       name: 'GeoPoint',
 *       fields: {
 *         lat: { type: new GraphQLNonNull(GraphQLFloat) },
 *         lon: { type: new GraphQLNonNull(GraphQLFloat) },
 *         alt: { type: GraphQLFloat, defaultValue: 0 },
 *       }
 *     });
 *
 */
var GraphQLInputObjectType = exports.GraphQLInputObjectType = function () {
  function GraphQLInputObjectType(config) {
    _classCallCheck(this, GraphQLInputObjectType);

    (0, _invariant2.default)(config.name, 'Type must be named.');
    (0, _assertValidName.assertValidName)(config.name);
    this.name = config.name;
    this.description = config.description;
    this._typeConfig = config;
  }

  GraphQLInputObjectType.prototype.getFields = function getFields() {
    return this._fields || (this._fields = this._defineFieldMap());
  };

  GraphQLInputObjectType.prototype._defineFieldMap = function _defineFieldMap() {
    var _this3 = this;

    var fieldMap = resolveThunk(this._typeConfig.fields);
    (0, _invariant2.default)(isPlainObj(fieldMap), this.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');
    var fieldNames = Object.keys(fieldMap);
    (0, _invariant2.default)(fieldNames.length > 0, this.name + ' fields must be an object with field names as keys or a ' + 'function which returns such an object.');
    var resultFieldMap = {};
    fieldNames.forEach(function (fieldName) {
      (0, _assertValidName.assertValidName)(fieldName);
      var field = _extends({}, fieldMap[fieldName], {
        name: fieldName
      });
      (0, _invariant2.default)(isInputType(field.type), _this3.name + '.' + fieldName + ' field type must be Input Type but ' + ('got: ' + String(field.type) + '.'));
      resultFieldMap[fieldName] = field;
    });
    return resultFieldMap;
  };

  GraphQLInputObjectType.prototype.toString = function toString() {
    return this.name;
  };

  return GraphQLInputObjectType;
}();

// Also provide toJSON and inspect aliases for toString.

GraphQLInputObjectType.prototype.toJSON = GraphQLInputObjectType.prototype.inspect = GraphQLInputObjectType.prototype.toString;

/**
 * List Modifier
 *
 * A list is a kind of type marker, a wrapping type which points to another
 * type. Lists are often created within the context of defining the fields of
 * an object type.
 *
 * Example:
 *
 *     const PersonType = new GraphQLObjectType({
 *       name: 'Person',
 *       fields: () => ({
 *         parents: { type: new GraphQLList(Person) },
 *         children: { type: new GraphQLList(Person) },
 *       })
 *     })
 *
 */
var GraphQLList = exports.GraphQLList = function () {
  function GraphQLList(type) {
    _classCallCheck(this, GraphQLList);

    (0, _invariant2.default)(isType(type), 'Can only create List of a GraphQLType but got: ' + String(type) + '.');
    this.ofType = type;
  }

  GraphQLList.prototype.toString = function toString() {
    return '[' + String(this.ofType) + ']';
  };

  return GraphQLList;
}();

// Also provide toJSON and inspect aliases for toString.

GraphQLList.prototype.toJSON = GraphQLList.prototype.inspect = GraphQLList.prototype.toString;

/**
 * Non-Null Modifier
 *
 * A non-null is a kind of type marker, a wrapping type which points to another
 * type. Non-null types enforce that their values are never null and can ensure
 * an error is raised if this ever occurs during a request. It is useful for
 * fields which you can make a strong guarantee on non-nullability, for example
 * usually the id field of a database row will never be null.
 *
 * Example:
 *
 *     const RowType = new GraphQLObjectType({
 *       name: 'Row',
 *       fields: () => ({
 *         id: { type: new GraphQLNonNull(GraphQLString) },
 *       })
 *     })
 *
 * Note: the enforcement of non-nullability occurs within the executor.
 */

var GraphQLNonNull = exports.GraphQLNonNull = function () {
  function GraphQLNonNull(type) {
    _classCallCheck(this, GraphQLNonNull);

    (0, _invariant2.default)(isType(type) && !(type instanceof GraphQLNonNull), 'Can only create NonNull of a Nullable GraphQLType but got: ' + (String(type) + '.'));
    this.ofType = type;
  }

  GraphQLNonNull.prototype.toString = function toString() {
    return this.ofType.toString() + '!';
  };

  return GraphQLNonNull;
}();

// Also provide toJSON and inspect aliases for toString.

GraphQLNonNull.prototype.toJSON = GraphQLNonNull.prototype.inspect = GraphQLNonNull.prototype.toString;


text:
package me.roybailey.springboot.graphql.fetchers;

import graphql.kickstart.servlet.context.DefaultGraphQLServletContext;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import lombok.extern.slf4j.Slf4j;
import me.roybailey.data.schema.UserDto;
import me.roybailey.springboot.service.UserAdaptor;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.http.HttpHeaders;

import java.util.Enumeration;
import java.util.List;

/**
 * Instantiated by graphql-java library so we need to hook into Spring to get other beans.
 */
@Slf4j
public class UserListFetcher implements DataFetcher<List<UserDto>>, ApplicationListener<ContextRefreshedEvent> {

    UserAdaptor userAdaptor;

    public UserListFetcher(UserAdaptor userAdaptor) {
        this.userAdaptor = userAdaptor;
    }

    @Override
    public List<UserDto> get(DataFetchingEnvironment environment) {
        DefaultGraphQLServletContext context = environment.getContext();
        Enumeration<String> headers = context.getHttpServletRequest().getHeaders("");
        while (headers.hasMoreElements()) {
            String header = headers.nextElement();
            String value = context.getHttpServletRequest().getHeader(header);
            log.info("HttpHeader {} {}", header, value);
        }
        log.info("getArguments {}", environment.getArguments());
        List<UserDto> allUsers = userAdaptor.getAllUsers();
        return allUsers;
    }

    // only needed for annotations schema as it instantiates fetchers outside spring
    public UserListFetcher() {}

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        userAdaptor = contextRefreshedEvent.getApplicationContext().getBean(UserAdaptor.class);
    }
}


text:
package com.zimbra.common.localconfig;

public class ConfigException extends Exception {
    public ConfigException(String key) {
        super(key);
    }
}


text:
namespace StructuralPatterns
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public interface Image
    {
        void display();
    }
}


text:
// 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.

//
//  APCarDBAutoCompleteItemsSource.m
//  OilSavings
//
//  Created by Andi Palo on 7/21/14.
//  Copyright (c) 2014 Andi Palo. All rights reserved.
//

#import "APCarDBAutoCompleteItemsSource.h"
//Use this it is almost identical
#import "TRGoogleMapsSuggestion.h"
#import <sqlite3.h>

@implementation APCarDBAutoCompleteItemsSource{
    NSUInteger _minimumCharactersToTrigger;
    NSString *_databasePath;
    NSString *_brand;
    sqlite3 *_carDB;
    EDIT_TYPE _type;
    BOOL _requestToReload;
    BOOL _loading;
}

- (id)initWithMinimumCharactersToTrigger:(NSUInteger)minimumCharactersToTrigger andFieldType:(EDIT_TYPE) tt{
    self = [super init];
    if (self)
    {
        _type = tt;
        _minimumCharactersToTrigger = minimumCharactersToTrigger;
    }

    return self;
}

- (id)initWithMinimumCharactersToTrigger:(NSUInteger)minimumCharactersToTrigger andFieldType:(EDIT_TYPE) tt andBrand:(NSString*)bb{
    self = [self initWithMinimumCharactersToTrigger:minimumCharactersToTrigger andFieldType:tt];
    if (self)
    {
        _brand = bb;
    }

    return self;
}
- (void)setBrandString:(NSString*)bb{
    _brand = bb;
}
- (void)itemsFor:(NSString *)query whenReady:(void (^)(NSArray *))suggestionsReady
{
    @synchronized (self)
    {
        if (_loading)
        {
            _requestToReload = YES;
            return;
        }

        _loading = YES;
        [self requestSuggestionsFor:query whenReady:suggestionsReady];
    }
}

- (void)requestSuggestionsFor:(NSString *)query whenReady:(void (^)(NSArray *))suggestionsReady
{
    //Root filepath
    NSString *appDir = [[NSBundle mainBundle] resourcePath];

    _databasePath = [[NSString alloc] initWithString: [appDir stringByAppendingPathComponent:@"car.sqlite"]];

    NSFileManager *filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: _databasePath ] == NO){
        ALog("Error here buddy , could not find car db file");
    }else{
        const char *dbpath = [_databasePath UTF8String];

        if (sqlite3_open(dbpath, &_carDB) != SQLITE_OK){
            ALog("Failed to open/create database");
        }
        //Load data

        NSString *querySQL;
        sqlite3_stmt    *statement;

        if (_type == kBrandEdit) {
            querySQL = [NSString stringWithFormat:@"SELECT brand FROM brands where brand like '%%%@%%'",query];
        }else if (_type == kModelEdit){
            if (_brand != nil) {
                querySQL = [NSString stringWithFormat:@"SELECT model FROM models where brandID = (SELECT id from brands WHERE brand = '%@') and model like '%%%@%%'",_brand, query];
            }else{
                querySQL = [NSString stringWithFormat:@"SELECT model FROM models where model like '%%%@%%'",query];
            }
        }

//        ALog("Items for car model %@",querySQL);

        const char *query_stmt = [querySQL UTF8String];

        if (sqlite3_prepare_v2(_carDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            NSMutableArray *result = [[NSMutableArray alloc]init];
//            ALog("Query returns something");

            while (sqlite3_step(statement) == SQLITE_ROW) {
                NSString *info = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
                TRGoogleMapsSuggestion *suggestion = [[TRGoogleMapsSuggestion alloc] initWith:info];
                [result addObject:suggestion];
            }
            sqlite3_finalize(statement);
            if (suggestionsReady)
                suggestionsReady(result);

            @synchronized (self)
            {
                _loading = NO;

                if (_requestToReload)
                {
                    _requestToReload = NO;
                    [self itemsFor:query whenReady:suggestionsReady];
                }
            }
        }else{

        }

        sqlite3_close(_carDB);
    }

}

+ (NSDictionary*) getIDForCarModel:(NSString*)model{
    //Root filepath
    NSString *appDir = [[NSBundle mainBundle] resourcePath];

    NSString *dataPath = [[NSString alloc] initWithString: [appDir stringByAppendingPathComponent:@"car.sqlite"]];

    NSFileManager *filemgr = [NSFileManager defaultManager];
    sqlite3 *db;

    NSMutableDictionary * result = [[NSMutableDictionary alloc] init];

    if ([filemgr fileExistsAtPath: dataPath ] == NO){
        ALog("Error here buddy , could not find car db file");
    }else{
        const char *dbpath = [dataPath UTF8String];

        if (sqlite3_open(dbpath, &db) != SQLITE_OK){
            ALog("Failed to open/create database");
        }
        //Load data

        NSString *querySQL;
        sqlite3_stmt    *statement;

        querySQL = [NSString stringWithFormat:@"SELECT id,energy FROM models where model = '%@'",model];

        const char *query_stmt = [querySQL UTF8String];
        int rowID;
        if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW) {
                rowID = sqlite3_column_int(statement, 0);
                [result setValue:[NSNumber numberWithInt:rowID] forKey:@"modelID"];

                NSString *energy = [NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)];
                if ([energy isEqualToString:@"gasoline"]) {
                    [result setValue:[NSNumber numberWithInt:kEnergyGasoline] forKey:@"energy"];
                }else if ([energy isEqualToString:@"diesel"]){
                    [result setValue:[NSNumber numberWithInt:kEnergyDiesel] forKey:@"energy"];
                }
//                ALog("Energy %@ and id %d",energy, rowID);
            }
            sqlite3_finalize(statement);
        }

        /* Find all params */
        querySQL = [NSString stringWithFormat:@"SELECT * FROM parameters where modelID = %d",rowID];
        query_stmt = [querySQL UTF8String];
        if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW) {
                [result setValue:[NSNumber numberWithDouble:sqlite3_column_double(statement, 1)] forKey:@"pA"];
                [result setValue:[NSNumber numberWithDouble:sqlite3_column_double(statement, 2)] forKey:@"pB"];
                [result setValue:[NSNumber numberWithDouble:sqlite3_column_double(statement, 3)] forKey:@"pB"];
                [result setValue:[NSNumber numberWithDouble:sqlite3_column_double(statement, 4)] forKey:@"pD"];

            }
            sqlite3_finalize(statement);
        }
        /* Find brand name also */
        querySQL = [NSString stringWithFormat:@"SELECT brand FROM brands where id = (SELECT brandID from models where model = '%@')",model];
        query_stmt = [querySQL UTF8String];
        if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW) {
                [result setValue:[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 0)] forKey:@"brand"];
            }
            sqlite3_finalize(statement);
        }
    }
    return result;
}
- (NSUInteger)minimumCharactersToTrigger
{
    return _minimumCharactersToTrigger;
}

@end


text:
<?php

namespace Awa\BussinessBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Awa\BussinessBundle\Entity\AAplication;
use Awa\BussinessBundle\Entity\Distributor;
use Awa\BussinessBundle\Form\AAplicationType;
use Awa\BussinessBundle\Form\AAplicationDistributorType;

use Awa\BussinessBundle\Form\Filter\AwaAplicationFilterType;

/**
 * AAplication controller.
 *
 * @Route("/aplication")
 */
class AAplicationController extends Controller
{

    /**
     * Lists all AAplication entities.
     *
     * @Route("/", name="aplication")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AwaBussinessBundle:AAplication')->findAll();

        $form = $this->get('form.factory')->create(new AwaAplicationFilterType());
        if ($this->get('request')->query->has('submit-filter')) {
            // bind values from the request
            $form->bind($this->get('request'));

            // initialize a query builder
            $filterBuilder = $this->get('doctrine.orm.entity_manager')
                ->getRepository('AwaBussinessBundle:AAplication')
                ->createQueryBuilder('e');

            // build the query from the given form object
            $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $filterBuilder);

            $resultQuery = $filterBuilder->getQuery();
            $fiteredEntities = $resultQuery->getArrayResult();

            return array('entities' => $fiteredEntities);
        }

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Displays a form to filter  existing Cars entity.
     *
     * @Route("/filter/", name="aplication_filter")
     *
     *
     */
    public function baseFilterAction()
    {
        $form = $this->get('form.factory')->create(new AwaAplicationFilterType());

        if (($this->get('request')->query->has('submit-filter')) || $this->get('request')->isXmlHttpRequest()) {
            // bind values from the request
            $form->bind($this->get('request'));

            // initialize a query builder
            $filterBuilder = $this->get('doctrine.orm.entity_manager')
                ->getRepository('AwaBussinessBundle:AAplication')
                ->createQueryBuilder('e');

            // build the query from the given form object
            $this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($form, $filterBuilder);

            $resultQuery = $filterBuilder->getQuery();
            $fiteredEntities = $resultQuery->getArrayResult();

            if($this->get('request')->isXmlHttpRequest())
            {
              $response = new JsonResponse();
              $response->setData(array(
                'entities' => json_encode($fiteredEntities)
              ));
              return $response;
            }

            return $this->render('AwaBussinessBundle:AAplication:showFilterResults.html.twig', array(
              'entities' => $fiteredEntities,
              ));
        }

        return $this->render('AwaBussinessBundle:AAplication:baseFilter.html.twig', array(
            'form' => $form->createView(),
        ));
    }

    /**
     * Creates a new AAplication entity.
     *
     * @Route("/", name="aplication_create")
     * @Method("POST")
     * @Template("AwaBussinessBundle:AAplication:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity  = new AAplication();
        $form = $this->createForm(new AAplicationType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            foreach($form->getData()->getImages() as $image)
            {
              $image->upload();
              $image->setAaplication($entity);
              $em->persist($image);
            }
            $em->flush();

            return $this->redirect($this->generateUrl('aplication_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a new AAplication entity.
     *
     * @Route("/", name="aplication_distributor_create")
     * @Method("POST")
     * @Template("AwaBussinessBundle:AAplication:new.html.twig")
     */
    public function createAppDistributorAction(Request $request)
    {
        $entity  = new AAplication();
        $form = $this->createForm(new AAplicationDistributorType(), $entity);
        $form->bind($request);
        $user = $this->get('security.context')->getToken()->getUser();

        $distributor = $em->getRepository('AwaBussinessBundle:Distributor')->findOneBy(array('user' => $user));
        $entity->setDistributor($distributor);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('aplication_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to create a new AAplication entity.
     *
     * @Route("/new", name="aplication_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new AAplication();
         $em = $this->getDoctrine()->getManager();
        $images = $em->getRepository('AwaBussinessBundle:AplicationImage')->findAll();
        $entity->getImages($images);
        $form   = $this->createForm(new AAplicationType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

     /**
     * Displays a form to create a new AAplication entity.
     *
     * @Route("/add", name="aplication_distributor_new")
     * @Method("POST")
     * @Template()
     */
    public function addAction()
    {
        $entity = new AAplication();
        $form   = $this->createForm(new AAplicationDistributorType(), $entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a AAplication entity.
     *
     * @Route("/{id}", name="aplication_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AwaBussinessBundle:AAplication')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find AAplication entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing AAplication entity.
     *
     * @Route("/{id}/edit", name="aplication_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AwaBussinessBundle:AAplication')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find AAplication entity.');
        }

        $editForm = $this->createForm(new AAplicationType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing AAplication entity.
     *
     * @Route("/{id}", name="aplication_update")
     * @Method("PUT")
     * @Template("AwaBussinessBundle:AAplication:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('AwaBussinessBundle:AAplication')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find AAplication entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new AAplicationType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('aplication_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a AAplication entity.
     *
     * @Route("/{id}", name="aplication_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AwaBussinessBundle:AAplication')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find AAplication entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('aplication'));
    }

    /**
     * Creates a form to delete a AAplication entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm();
    }
}